示例表 tb 数据如下
id value
—————
1 aa
1 bb
2 aaa
2 bbb
2 ccc
SELECT id, [val] = ( SELECT [value] + ',' FROM tb AS b WHERE b.id = a.id FOR XML PATH('') ) FROM tb AS a
显示结果
1 aa,bb,
1 aa,bb,
2 aaa,bbb,ccc,
2 aaa,bbb,ccc,
2 aaa,bbb,ccc,
-----------------------------
SELECT id, [val]=( SELECT [value] +',' FROM tb AS b WHERE b.id = a.id FOR XML PATH('') ) FROM tb AS a GROUP BY id
显示结果
1 aa,bb,
2 aaa,bbb,ccc,
SELECT id, [val]=STUFF( (SELECT ','+[value] FROM tb AS b WHERE b.id = a.id FOR XML PATH('')) , 1 , 1 , '' ) FROM tb AS a GROUP BY id
显示结果
1 aa,bb
2 aaa,bbb,ccc
STUFF 函数将字符串插入另一字符串。它在第一个字符串中从开始位置删除指定长度的字符;然后将第二个字符串插入第一个字符串的开始位置。
STUFF ( character_expression , start , length ,character_expression_insert )
SELECT id, [val]= REPLACE( (SELECT [value] AS [data()] FROM tb AS b WHERE b.id = a.id FOR XML PATH('')) , ' ', ',') FROM tb AS a GROUP BY id
结果与上面一样。
解析:[data()] 这里据说是起到一个类似数组的作用,具体用法还要再查。
如果外围不用REPLACE函数包住,则返回的结果是 aaa bbb ccc ,每项之间有空格,所以最后用REPLACE函数将所有空格替换成逗号。