Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Concatenate rows with comma separated string

5.00/5 (7 votes)
6 Dec 2012CPOL 38K  
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)