sql server 2005 and above, 合并多行为一行,并返回
数据集:表名:tb_test
id name
1 abc
2 xyz
3 test
想一次性返回:1,abc|2,xyz|3,test
具体的测试SQL如下:
DECLARE @Sample TABLE (ID INT, NAME VARCHAR(50))
INSERT @Sample
SELECT 1, 'a是cdl' UNION ALL
SELECT 2, 'bcdl' UNION ALL
SELECT 3, 'ccdl' UNION ALL
SELECT 4, 'dcdl'
SELECT CAST(STUFF(g.y, 1, 1, '') AS VARCHAR(100)) AS result
FROM (
SELECT DISTINCT '|' + CAST(id AS VARCHAR(11))+','+NAME
FROM @Sample
FOR XML PATH('')
) AS g(y)
INSERT @Sample
SELECT 1, 'a是cdl' UNION ALL
SELECT 2, 'bcdl' UNION ALL
SELECT 3, 'ccdl' UNION ALL
SELECT 4, 'dcdl'
SELECT CAST(STUFF(g.y, 1, 1, '') AS VARCHAR(100)) AS result
FROM (
SELECT DISTINCT '|' + CAST(id AS VARCHAR(11))+','+NAME
FROM @Sample
FOR XML PATH('')
) AS g(y)