Showing posts with label list using select. Show all posts
Showing posts with label list using select. Show all posts

Monday, October 29, 2012

How to create a comma delimited list using SELECT clause from table column?



How to create a comma delimited list using SELECT clause from table column?

USE
 tempdb;
GO

/*Create sample table and data*/
CREATE TABLE sampleTable (id INT, VALUE VARCHAR(150))
GO

INSERT dbo.sampleTable
        ( id, VALUE )
VALUES  ( 10, 'Value 1' ),( 11, 'Value 2' ),( 12, 'Value 3' ),( 13, 'Value 4' ),( 14, 'Value 5' )
GO

DECLARE @CSV_str NVARCHAR(500);
/*Collecting all values in Value column to @CSV_str variable*/
SELECT @CSV_str = ISNULL(@CSV_str + ',','') + VALUE FROM dbo.sampleTable

PRINT @CSV_str


/*drop sample table*/

DROP TABLE dbo.sampleTable