Click here to Skip to main content
Click here to Skip to main content

Tagged as

Concatenate rows with comma separated string

, 6 Dec 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
Concatenate rows with comma separated string in SQL.

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

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

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

Or another way is:

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:

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

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

or:

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)

Share

About the Author

Ravi Tuvar
Technical Lead IntelliMedia Networks, Inc
India India
No Biography provided
Follow on   Twitter   LinkedIn

Comments and Discussions

 
GeneralMy vote of 5 PinmemberSimon Lee Shugar19-Jun-13 3:00 
GeneralMy vote of 5 PinmemberPaulo Roberto Elias7-Nov-12 5:42 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.141220.1 | Last Updated 6 Dec 2012
Article Copyright 2012 by Ravi Tuvar
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid