Search code examples
sqlsql-serverlistfunctionconcatenation

How can I combine multiple rows into a comma-delimited list in SQL Server 2005?


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

SELECT X, Y FROM POINTS

It returns results like so:

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

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

Is there a way to do this using just SQL?


Solution

  • 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)