Sql 存储过程接收ID的逗号sep列表要检索解码值的逗号sep列表
如果我的SP中的部门ID传入列表如下所示:Sql 存储过程接收ID的逗号sep列表要检索解码值的逗号sep列表,sql,xml,sql-server-2008,tsql,Sql,Xml,Sql Server 2008,Tsql,如果我的SP中的部门ID传入列表如下所示: DECLARE @x varchar(250), @xx xml set @x = '3, 9, 10, 12, 14' 我可以轻松地将其转换为XML并按如下方式进行查询: DECLARE @x varchar(250), @xx xml set @x = '3, 9, 10, 12, 14' 返回: set @xx = '<xml><e>' + REPLACE(@x,', ','</e><e>'
DECLARE @x varchar(250), @xx xml
set @x = '3, 9, 10, 12, 14'
我可以轻松地将其转换为XML并按如下方式进行查询:
DECLARE @x varchar(250), @xx xml
set @x = '3, 9, 10, 12, 14'
返回:
set @xx = '<xml><e>' + REPLACE(@x,', ','</e><e>') + '</e></xml>'
select @xx
select @xx.query('for $d in /xml/e return data($d)')
当我事先知道部门名称时,我可以使用XML路径手动获取以逗号分隔的部门名称列表
3 9 10 12 14
但是,我认为我应该能够通过上面的XML实现这一点:
select SUBSTRING((SELECT (', '+DeptName) from vDepartments where DeptID in (3, 9, 10, 12, 14) for xml path('')), 3, 1000)
我将把参数中的id放在一个表变量中,并在针对vDepartment的连接中使用它
select SUBSTRING((SELECT (', '+DeptName) from vDepartments where DeptID in @xx.query('for $d in /xml/e return string($d)') for xml path('')), 3, 1000)
怎么了?你已经表达了你想做什么。。。但当你尝试的时候不会发生什么。
;with cte(ID, Rest) as
(
select cast(left(@x, charindex(',', @x+',')-1) as int),
stuff(@x, 1, charindex(',', @x+','), '')+','
where len(@x) > 0
union all
select cast(left(Rest, charindex(',', Rest)-1) as int),
stuff(Rest, 1, charindex(',', Rest), '')
from cte
where len(Rest) > 1
)
select stuff(
(select ', '+DeptName
from vDepartments as D
inner join cte as T
on D.DeptID = T.ID
for xml path(''), type).value('.', 'varchar(max)'), 1, 2, '')