我有两张桌子:
tbl A tbl B
ID | Value ID | tblA_ID | Qty
1 | CGK 1 | 2,3 | 100
2 | BNK 2 | 2 | 85
3 | DPK 3 | 1,3,4 | 200
4 | CMG 4 | 1,2 | 120
加入时我想要这个输出:
tblBID| tblA_Values | Qty
1 | BNK,DPK | 100
2 | BNK | 85
3 | CGK,DPK,CMG | 200
4 | CGK,BNK | 120
我不知道搜索问题和答案的关键字,这就是我发布此问题的原因。
答案 0 :(得分:0)
不仅仅是简单的加入。实际上有三个主要部分需要关注。
1)解析或拆分数据
2)使用tblA
加入已解析的结果3)通过XML / Stuff()
重建字符串如果您无法使用UDF,则可以轻松将其修改为内联流程。
SQL or dbFiddle
Select tblBID = A.ID
,tblA_Values = B.S
,A.Qty
From TblB A
Cross Apply (
Select S=Stuff((Select ',' +Value
From (
Select B1.RetSeq,Value
From [dbo].[udf-Str-Parse](A.[tblA_ID],',') B1
Join TblA B2 on B1.RetVal = B2.ID
) X1
Order By RetSeq
For XML Path (''))
,1,1,'')
)B
<强>返回强>
感兴趣的UDF
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 A
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',' ')
编辑 - 内联选项(无UDF)
Select tblBID = A.ID
,tblA_Values = B.S
,A.Qty
From TblB A
Cross Apply (
Select S=Stuff((Select ',' +Value
From (
Select B1.RetSeq,Value
From (
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(A.[tblA_ID],',','§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>' as xml).query('.')) as A
Cross Apply x.nodes('x') AS B(i)
) B1
Join TblA B2 on B1.RetVal = B2.ID
) X1
Order By RetSeq
For XML Path (''))
,1,1,'')
)B