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

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


Thanks for the quick and helpful answers guys!

I just found another fast way to do this too:

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

Credit goes to this guy:

http://geekswithblogs.net/mnf/archive/2007/10/02/t-sql-user-defined-function-to-concatenate-column-to-csv-string.aspx


DECLARE @XYList varchar(MAX)SET @XYList = ''SELECT @XYList = @XYList + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y) + ','FROM POINTS-- Remove last commaSELECT LEFT(@XYList, LEN(@XYList) - 1)


Using the COALESCE trick, you don't have to worry about the trailing comma:

DECLARE @XYList AS varchar(MAX) -- Leave as NULLSELECT @XYList = COALESCE(@XYList + ',', '') + CONVERT(varchar, X) + ',' + CONVERT(varchar, Y)FROM POINTS