SQL Tip #6 – Transform Rows into Comma Separated Value (CSV)

This tutorial is about converting row values into a single column in the form of comma separated values (CSV).

Sample table 1:

Output 1:

Above output can be achieved with the help of the following:
1. For XML path
2. Stuff

For XML path(”) is used to concatenate rows values into one column.
Stuff – this function helps to replace a part of string with another string.

In order to achieve we can apply the following sql:

SELECT Main.City,
(
	SELECT ',' + c.CustomerName
	FROM Customer c
	WHERE c.City = Main.City
	FOR XML PATH('')

) AS CSV
FROM Customer AS Main
GROUP BY Main.City

We have achieved the expected result. However we can see an additional comma in the result set.

We can easily overcome this issue with the help of Stuff function.

SELECT Main.City, STUFF(
(
	SELECT ',' + c.CustomerName
	FROM Customer c
	WHERE c.City = Main.City
	FOR XML PATH('')

),1,1,'') AS CSV
FROM Customer AS Main
GROUP BY Main.City
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s