Click here to Skip to main content
15,881,139 members
Articles / Database Development / SQL Server
Tip/Trick

Concatenate rows with comma separated string

Rate me:
Please Sign up or sign in to vote.
5.00/5 (7 votes)
6 Dec 2012CPOL 37.5K   7   2
Concatenate rows with comma separated string in SQL.

Please use the following query when concatenating multiple rows with a single comma separated string (row):

SQL
DECLARE @iXml xml;
SELECT @iXml = (
  SELECT ProductName + ','
  FROM Northwind.dbo.Products
  FOR XML PATH);

SELECT @iXml.value('.','nvarchar(max)');

Or another way is:

SQL
SELECT STUFF((SELECT ',' + RTRIM(ProductName ) FROM Products FOR XML PATH('')),1,1,'') AS 'Products'

Now this block will return a string with comma separated rows..

If you want to get distinct values with a comma separated row.. then do this:

SQL
DECLARE @iXml xml;
 
SELECT @iXml = (
  SELECT distinct ProductName + ','
  FROM Northwind.dbo.Products
  FOR XML PATH);

SELECT @iXml.value('.','nvarchar(max)');

or:

SQL
SELECT STUFF((SELECT Distinct ',' + RTRIM(ProductName ) 
    FROM Products FOR XML PATH('')),1,1,'') AS 'Products'

This would be useful when you have to check between conditions in a SQL query.

Votes are welcome..!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead IntelliMedia Networks, Inc
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Simon Lee Shugar19-Jun-13 2:00
Simon Lee Shugar19-Jun-13 2:00 
GeneralMy vote of 5 Pin
Paulo Roberto Elias7-Nov-12 4:42
Paulo Roberto Elias7-Nov-12 4:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.