Pages

Sep 26, 2011

Converting records into comma separated values

MS-SQL Converting list of records into CSV
CREATE TABLE TestTable
(
	ID INT IDENTITY(1,1) PRIMARY KEY,
	[NAME] VARCHAR(50)
)
GO
INSERT INTO TestTable VALUES ('1')
INSERT INTO TestTable VALUES ('2')
INSERT INTO TestTable VALUES ('3')
INSERT INTO TestTable VALUES ('4')
INSERT INTO TestTable VALUES ('5')
INSERT INTO TestTable VALUES ('6')
INSERT INTO TestTable VALUES ('7')
GO
SELECT substring((SELECT ( ', ' + [Name] ) FROM TestTable FOR XML PATH( '' )), 3, 1000 )

Output:
1, 2, 3, 4, 5, 6, 7