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

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

4.67/5 (13 votes)
16 Oct 2014CPOL 153.1K  
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)