Get comma separated values from table column in sql server

Earlier we have gone through the way to get table from comma separated list. You can review below post for same.

  1. Comma separated string to table  using while loop in SQL
  2. Comma separated string to table using CTE in SQL
  3. comma separated string to table using XML in sql server

In this section we will do reverse, Get comma separated values from table column in sql server. We will go through the way to get comma separated values from tale column. Below is my simple table from which i need comma separated list of product category.

Product-table

There are multiple ways to generate comma separated list of category from above table.

1. Using COALESCE

DECLARE @CSV VARCHAR(MAX)
SET @CSV = ''

SELECT @CSV =
		COALESCE (CASE WHEN @CSV = ''
					   THEN CATEGORY
				  ELSE @CSV + ',' + CATEGORY END,'')
		FROM SALES

PRINT @CSV

2. Using XML PATH

DECLARE @CSV VARCHAR(MAX)
SET @CSV = ''

SELECT @CSV = LEFT(CATEGORY, LEN(CATEGORY) - 1)
			FROM (
				SELECT CATEGORY + ', '
				FROM Sales
				FOR XML PATH ('')
			) c (CATEGORY)

PRINT @CSV

The output for both of the above query is as below.

Output : Electronics, Electronics, Footwear, Clothing, Footwear, Clothing

Based on the result we can see that it is not generating the string with distinct values. As both of the above query are simple select, we can use DISTINCT in the query to make sure that the generated comma separated string have all the distinct values.

 

Leave a Reply