A 1 line script to concatenate all the values in a table’s column and output a single comma-separated value (CSV) string, using the all-powerful SQL Serve STUFF function (for removing the leading comma) with the FOR XML clause.
The code snippet below uses the Pubs sample database that comes free with MS SQL Server.
USE Pubs
GO
SELECT STUFF((SELECT ',' + au_fname FROM Authors FOR XML PATH('')),1, 1, '') AS Column2CSVString
The output of the code snippet is as follows.
Abraham,Reginald,Cheryl,Michel,Innes,Ann,Marjorie,Morningstar,Burt,Sheryl,Livia,Shiva,Charlene,Stearns,Heather,Michael,Sylvia,Albert,Anne,Meander,Dean,Dirk,Johnson,Akiko
To order the column values in ASC or DESC order, add the ORDER BY clause after the tablename as shown below.
USE Pubs
GO
SELECT STUFF((SELECT ',' + au_fname FROM Authors ORDER BY 1 ASC FOR XML PATH('')),1, 1, '') AS Column2CSVString
The output of the code snippet is as follows.
Abraham,Akiko,Albert,Ann,Anne,Burt,Charlene,Cheryl,Dean,Dirk,Heather,Innes,Johnson,Livia,Marjorie,Meander,Michael,Michel,Morningstar,Reginald,Sheryl,Shiva,Stearns,Sylvia
Finally, if you want to make this really generic and use dynamic SQL to pass in the column name and table name and delimiter, then let me know and I will post the code here.
Thanks! This worked like a charm
Thanks man
I was searching for this a long time. I used the “function” workaround, but this is far more compact.
Thank you :)
Just a quick note:
If your table is empty, the snippet above returns NULL, not an empty string.
Thanks for the code!
It works but only with sql 2000 +
Thank you!
hi
thanks for your post.
I need your help in my project.
As you explained I have made a column as a comma separated string. Now my problem is how to attach this string to datalist.
suppose if the string equals dsc1.jpg, dsc2.jpg, dsc3.jpg i want to attach this to datalist so that I can see 3 photos in a datalist
thanks in advance
@swapna. Take a look at this MSDN article. There are some source code snippets for the dataList also in the middle.
Hope that help…