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

2021-12-07 00:00:00 function list sql concatenation sql-server

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

Right now, I have a SQL Query like this one:

SELECT X, Y FROM POINTS

它返回这样的结果:

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

我想在一行中返回结果,就像这样(适合在 HTML 标签中使用):

I'd like to return results all in one row, like this (suitable for using in an HTML <AREA> tag):

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

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

Is there a way to do this using just SQL?

推荐答案

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)

相关文章