Sunday, March 4, 2007

Table Column To CSV

The following query converts a column of data in a SQL table to a comma-delimited string. This works great for tables with a few hundred rows and limited to the size of the VARCHAR data type. A TEXT field can also be use if needed for large tables, but requires a little more work.

DECLARE @CSV VARCHAR(1000)
DECLARE @Delimiter CHAR(1)

SET @Delimiter = ','

SELECT
@CSV = COALESCE(@CSV + @Delimiter, '') + lastname FROM dbo.employees

PRINT @CSV

No comments: