Get Comma Separated Value From SQL Select Statement

By using XML PATH we can get comma separated list from SQL select statement.
For example here i am creating one demo table as below
DECLARE @tbl TABLE (str NVARCHAR(MAX))

Now insert value in @tbl table as
INSERT INTO @tbl( str ) VALUES (‘test1’)
INSERT INTO @tbl( str ) VALUES (‘test2’)
INSERT INTO @tbl( str ) VALUES (‘test3’)

Data looks in @tbl table as below

sql_1

Now write query as below

SELECT DISTINCT
STUFF((SELECT distinct ‘,’ + c1.[str]
FROM @tbl c1
FOR XML PATH(”), TYPE).value(‘.’, ‘NVARCHAR(MAX)’),1,1,”) COMMA_VAL
FROM @tbl;

Now run all queries as below and you will get output as below image

DECLARE @tbl TABLE (str NVARCHAR(MAX))
INSERT INTO @tbl( str ) VALUES  (‘test1’)
INSERT INTO @tbl( str ) VALUES  (‘test2’)
INSERT INTO @tbl( str ) VALUES  (‘test3’)

SELECT DISTINCT
STUFF((SELECT distinct ‘,’ + c1.[str]
FROM @tbl c1
FOR XML PATH(”), TYPE).value(‘.’, ‘NVARCHAR(MAX)’),1,1,”) COMMA_VAL
FROM @tbl;

sql_2

 

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