表A 表B
需要的结果:
第一步:运用 for xml path 和 charindex
select A.id,(
select ','+B.name from B
where charindex( ','+B.code , ','+A.code+',')>0
order by B.code
for xml path('')
)
from A
结果:
charindex :
CHARINDEX ( expression1 , expression2)
解析: expression1 必需 ---要查找的子字符串
expression2 必需 ---父字符串
在上表中 where charindex( ','+B.code , ','+A.code+',')>0
','+B.code 是 ','+A.code+',' 的子集;
例如:,01 ,02 ,03 ,04 为B表
,01, ,01,02, ,01,02,03, ,01,02,03,04, 为表A
第二部:用stuff去掉第一个逗号
select A.id,stuff((
select ','+B.name from B
where charindex( ','+B.code , ','+A.code+',')>0
order by B.code
for xml path('')
),1,1,'') as name
from A
实例:select STUFF('abcdefg',3,2,'123') --结果为'ab123efg'
'abcdefg'原字符串,3为开始的位置,2为删除的长度,123位插入的字符
最后结果: