2017-03-07 189 views
0

經理主表逗號分割在SQL

enter image description here

而且用戶表分隔字符串

enter image description here

我使用主表要以逗號分隔的經理姓名。

我想造成這種形式

enter image description here

我的查詢是這樣的

declare @ststring varchar(max)= select manager 
from customer 

    CREATE TABLE #tblUserCustomer (inCustomerID iNT) 

Insert into #tblUserCustomer 
select stvalue from dbo.getlistfrmcommaseprated_int('1,2,4') 
declare @stcscont varchar(1000) 
select @stcscont = (select Um.Name + ',' from master um 
        join #tblUserCustomer T on t.inCustomerID = um.inuserid 
        FOR XML PATH('') 
        ) 
print @stcscont 
drop table #tblUserCustomer 

此查詢可以幫助充滿了對單個數據 但我有多個排

+0

我想這是在用戶表中給出經理姓名的相關管理者的ID。 –

回答

1

我沒有你的解析函數,所以我替換了我的。 [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) 
+0

嗨它給錯誤「無效的對象名稱」dbo.udf-Str-Parse。「 –

+0

@radhasingh閱讀我的答案的第一行開心提供我的分析功能。剛假設你不想要兩個 –

+0

@radhasingh添加了我的解析函數 –