select *
into #tempA
from (
select '1' id,'1,2,3,4,5' name
union
select '2','2,3,4,5,6'
) aa
1.2、数据处理,把逗号分割的由列转行
###特别注意:如果内容中包含符号&就报错这样导致报错XML 分析: 行 1,字符 39,需要分号
###这时候就要转换
##CROSS APPLY (
## SELECT CAST('<row>' + REPLACE(REPLACE(name, '&', ##'&'),
##',','</row><row>')+ '</row>' AS XML) AS xmlcode
##) C1
SELECT
--列名
ROW_NUMBER() over(order by (select 1)) as row_id,
a.id,C1.*,item.c.value('.', 'varchar(50)') AS list
FROM #tempA a
CROSS APPLY (
SELECT CAST('<row>' + REPLACE(name, ',','</row><row>')+ '</row>' AS XML) AS xmlcode
) C1
CROSS APPLY xmlcode.nodes('*') item ( c );
案例二、查看逗号里的字符串是否存在
SELECT * FROM [news] t where charindex( ',' +'a'+',',',' +t.news_tag+',')>0
逗号拼接例子
SELECT STUFF((
SELECT ',' + CAST(b.id AS VARCHAR(50))
FROM #tempI a
LEFT JOIN uf_db_AuthorityList b ON a.RoleCode = b.Code
WHERE a.code = 'NC-CR-DH-M001'
FOR XML PATH('')
), 1, 1, '') AS LongNames;
----实战例子
select '微信工作群' as SystemName,a.Name,a.FRemark,
(SELECT STUFF((
SELECT ',' + CAST(a2.qcy AS VARCHAR(50))
FROM uf_db_WechatChat_dt1 a2
WHERE a2.mainid = a.id
FOR XML PATH('')
), 1, 1, '')) AS LongNames
from uf_db_WechatChat a
where a.FStatus=1
----去重实战例子
select '微信工作群' as SystemName,a.Name,a.FRemark,
(SELECT STUFF((
SELECT ',' + CAST(a2.qcy AS VARCHAR(50))
FROM #TEMPB a2
WHERE a2.mainid = a.id
GROUP BY a2.qcy
FOR XML PATH('')
), 1, 1, '')) AS LongNames
from #TEMPA a
where a.FStatus=1 and a.id=1