我沒有你的解析函數,所以我替換了我的。 [dbo].[udf-Str-Parse]
返回RETVAL
一些示例數據
Declare @Manager table (ID int,Name varchar(25))
Insert Into @Manager values
(1,'Ajay'),
(2,'Sarita'),
(3,'Akash'),
(4,'Niti')
Declare @User table (ID int,Name varchar(25),Manager varchar(25))
Insert Into @User values
(1,'Javed','1,3'),
(2,'Ruma' ,'1,4')
實際查詢
Select A.*
,ManagerName = B.String
From @User A
Cross Apply (
Select String = Stuff((Select ',' +Name
From (
Select M.Name,ML.RetSeq
From @Manager M
Join [dbo].[udf-Str-Parse](A.Manager,',') ML
on M.ID=ML.RetVal
) X
Order By RetSeq
For XML Path ('')),1,1,'')
) B
返回
ID Name Manager ManagerName
1 Javed 1,3 Ajay,Akash
2 Ruma 1,4 Ajay,Niti
編輯 - 添加了我的解析功能
CREATE FUNCTION [dbo].[udf-Str-Parse] (@String varchar(max),@Delimiter varchar(10))
Returns Table
As
Return (
Select RetSeq = Row_Number() over (Order By (Select null))
,RetVal = LTrim(RTrim(B.i.value('(./text())[1]', 'varchar(max)')))
From (Select x = Cast('<x>' + replace((Select replace(@String,@Delimiter,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as X
Cross Apply x.nodes('x') AS B(i)
);
--Thanks Shnugo for making this XML safe
--Select * from [dbo].[udf-Str-Parse]('Dog,Cat,House,Car',',')
--Select * from [dbo].[udf-Str-Parse]('John Cappelletti was here',' ')
--Select * from [dbo].[udf-Str-Parse]('this,is,<test>,for,< & >',',')
--Performance On a 5,000 random sample -8K 77.8ms, -1M 79ms (+1.16), -- 91.66ms (+13.8)
我想這是在用戶表中給出經理姓名的相關管理者的ID。 –