2011-06-15 18 views
1
DECLARE @x varchar(250), @xx xml 

的月列表。如果我在我的SP部门ID的传入的名单看起来是这样的:存储过程接收逗号月表ID要检索逗号解码值

set @x = '3, 9, 10, 12, 14' 

我可以很容易地将其转换成XML和查询它是这样的:

set @xx = '<xml><e>' + REPLACE(@x,', ','</e><e>') + '</e></xml>' 

select @xx 

返回:

<xml><e>3</e><e>9</e><e>10</e><e>12</e><e>14</e></xml> 

而且

select @xx.query('for $d in /xml/e return data($d)') 

返回:

3 9 10 12 14 

使用XML路径我可以手动获得逗号分隔的部门名称的列表,当我知道前手的DeptIDs

select SUBSTRING((SELECT (', '+DeptName) from vDepartments where DeptID in (3, 9, 10, 12, 14) for xml path('')), 3, 1000) 

但是,我认为我应该能够从上面的XML做到这一点:

select SUBSTRING((SELECT (', '+DeptName) from vDepartments where DeptID in @xx.query('for $d in /xml/e return string($d)') for xml path('')), 3, 1000) 
+0

什么是错误?你已经传达了你想要做的事情......但是当你尝试时不会发生什么。 – RThomas 2011-06-16 04:15:51

回答

0

我会把ID的从参数表中的变量和使用,在一个加入反对vDepartment

-- Comma separated parameter 
declare @x varchar(250) 
set @x = '3, 9, 10, 12, 14' 

-- Convert to xml 
declare @xx xml 
set @xx = '<xml><e>' + REPLACE(@x,', ','</e><e>') + '</e></xml>' 

-- Table variable to hold ID's from parameter 
declare @T table(ID int) 

-- Get ID's from xml 
insert into @T (ID) 
select N.value('.', 'int') 
from @xx.nodes('xml/e') as T(N) 

-- Use the table in a inner join. 
select stuff(
(select ', '+DeptName 
from vDepartments as D 
    inner join @T as T 
    on D.DeptID = T.ID 
for xml path(''), type).value('.', 'varchar(max)'), 1, 2, '') 

如果使用.value提取部门的逗号分隔的列表,你将不得不与<>&'"中没有麻烦部门名称。

编辑1

使用递归CTE获取的ID,而不是转换为XML一个版本。全部在一个查询中。

;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, '') 
+0

正是我需要的感谢 – BermudaLamb 2011-06-20 13:45:10