Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 384
Joshua Carmody Avatar asked Oct 07 '08 19:10

Joshua Carmody


People also ask

How do I combine rows and commas in SQL?

You can concatenate rows into single string using COALESCE method. This COALESCE method can be used in SQL Server version 2008 and higher. All you have to do is, declare a varchar variable and inside the coalesce, concat the variable with comma and the column, then assign the COALESCE to the variable.

How do I create a comma separated list in SQL?

How to Return Query Results as a Comma Separated List in SQL Server – STRING_AGG() Starting with SQL Server 2017, you can now make your query results appear as a list. This means you can have your result set appear as a comma-separated list, a space-separated list, or whatever separator you choose to use.


2 Answers

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

like image 132
Joshua Carmody Avatar answered Sep 23 '22 16:09

Joshua Carmody


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) 
like image 21
Ben Hoffstein Avatar answered Sep 20 '22 16:09

Ben Hoffstein