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?
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 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.
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 comma SELECT LEFT(@XYList, LEN(@XYList) - 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With