Convert Column values to Comma Separated Values

There are cases in sql server where sometimes we want to convert column values to comma separated values, here is a simple solution for same.


DECLARE @EmployeeTarget TABLE (EmployeeID INT)

INSERT INTO @EmployeeTarget(EmployeeID) VALUES(1)
INSERT INTO @EmployeeTarget(EmployeeID) VALUES(2)
INSERT INTO @EmployeeTarget(EmployeeID) VALUES(3)
INSERT INTO @EmployeeTarget(EmployeeID) VALUES(4)

SELECT STUFF(
(SELECT ',' + cast(EmployeeID AS VARCHAR) FROM @EmployeeTarget FOR XML PATH ('')), 1, 1, '') AS CSV

Here is the result of above sql query.

CSV_Result

 

 

Leave a Reply

Please log in using one of these methods to post your comment:

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