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

How to Get SQL Column Values as Comma Separated String using XML Path Method

Rate me:
Please Sign up or sign in to vote.
4.67/5 (13 votes)
16 Oct 2014CPOL 152.3K   25   9
Tip to get comma separated string for a column in SQL query using XML path method

Introduction

There are many scenarios where we have to show the values of column value as comma (or any other special character) separated string in result set.

This can be easily achieved using XML path method in SQL.

Using the SQL Query

Let's take an example of ProductDetails Table:

SQL
SELECT *  FROM  ProductDetails

Now suppose we want to fetch the list of products along with available colors where multiple colors are shown as comma separated string.

SQL
SELECT DISTINCT p.ProductName,
  STUFF((SELECT distinct ',' + p1.[Color]
         FROM ProductDetails p1
         WHERE p.ProductName = p1.ProductName
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'') Color
FROM ProductDetails p;

So in this way, we can fetch column value with comma separated string.

License

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


Written By
Software Developer
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

 
GeneralFeedback Pin
Devesh Kumar Singh20-Oct-19 0:29
Devesh Kumar Singh20-Oct-19 0:29 
QuestionGetting error when executing.. Pin
Member 1383705621-May-18 1:14
Member 1383705621-May-18 1:14 
QuestionThat Works But How Pin
Maulik_Modi23-Nov-15 17:58
Maulik_Modi23-Nov-15 17:58 
GeneralMy vote of 4 Pin
Suvendu Shekhar Giri5-Nov-15 18:05
professionalSuvendu Shekhar Giri5-Nov-15 18:05 
AnswerHow to get SQL column values as comma separated string using XML path method Pin
Sid_Joshi17-Oct-14 2:09
professionalSid_Joshi17-Oct-14 2:09 
GeneralMy vote of 1 Pin
Sid_Joshi17-Oct-14 1:00
professionalSid_Joshi17-Oct-14 1:00 
GeneralRe: My vote of 1 Pin
Matt Tomalin17-Oct-14 1:11
Matt Tomalin17-Oct-14 1:11 
I get that too. Changing "VALUE" to "value" works for me.
GeneralRe: My vote of 1 Pin
banitabisht17-Oct-14 1:13
banitabisht17-Oct-14 1:13 

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.