前言:该笔记以sqlserver为例
1、拼接一列数据为一个字符串
-- 把tableName表的colName列(字符串类型)的值 按 逗号拼接,结果名为name
select stuff((select ','+ colName from tableName for xml path ('')),1,1,'') as names
2、以逗号分隔的字符串组合成为多条记录
select
b.col colName -- colName是列别名
from -- 'a,b,c'是待分隔的字符串,替换成其它 逗号分隔的字符串即可(注意中英文标点)
(select col=convert(xml,' <root> <v>'+replace(col,',',' </v> <v>')+' </v> </root>') from (select 'a,b,c' as col) t )a
outer apply
(select col=C.v.value('.','nvarchar(100)') from a.col.nodes('/root/v')C(v)) b