如何在SQL Server 2005中将多行合并为逗号分隔的列表?

现在,我有一个这样的SQL查询:

SELECT X, Y FROM POINTS

它返回结果如下:

X    Y
----------
12   3
15   2
18   12
20   29

我想将结果全部返回一行,就像这样(适合在HTML <AREA>标记中使用):

XYLIST
----------
12,3,15,2,18,12,20,29

有没有办法仅使用SQL来做到这一点?

5个解决方案
77 votes

谢谢大家的快速有用的回答!

我也找到了另一种快速的方法:

SELECT  STUFF(( SELECT ',' + X + ',' + Y
                FROM Points
              FOR
                XML PATH('')
              ), 1, 1, '') AS XYList

归功于这个人:

[HTTP://geek是with blog上.net/免年费/archive/2007/10/02/他-SQL-user-defined-function-to-concatenate-column-to-CSV-string.aspx]

Joshua Carmody answered 2020-07-08T19:33:31Z
27 votes
DECLARE @XYList varchar(MAX)
SET @XYList = ''

SELECT @XYList = @XYList + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y) + ','
FROM POINTS

-- Remove last comma
SELECT LEFT(@XYList, LEN(@XYList) - 1)
Ben Hoffstein answered 2020-07-08T19:32:58Z
13 votes

使用COALESCE技巧,您不必担心结尾的逗号:

DECLARE @XYList AS varchar(MAX) -- Leave as NULL

SELECT @XYList = COALESCE(@XYList + ',', '') + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y)
FROM POINTS
Cade Roux answered 2020-07-08T19:33:53Z
6 votes

从SQL 2017开始,您可以使用STRING_AGG

SELECT STRING_AGG (X + ',' + Y, ',') AS XYLIST
FROM POINTS

[HTTPS://docs.Microsoft.com/恩-US/SQL/他-SQL/functions/string-啊嘎嘎-transact-SQL?view=SQL-server-2017]

Carter Medlin answered 2020-07-08T19:34:17Z
1 votes
DECLARE @s VarChar(8000)
SET @s = ''

SELECT @s = @s + ',' + CAST(X AS VarChar) + ',' + CAST(Y AS VarChar) 
FROM POINTS

SELECT @s 

只是摆脱领先的逗号

Peter answered 2020-07-08T19:34:37Z
translate from https://stackoverflow.com:/questions/180032/how-can-i-combine-multiple-rows-into-a-comma-delimited-list-in-sql-server-2005