I needed to convert a table of values into a comma separated string.

For example:

One
Two
Three

Desired result:


  One,Two,Three

I was reading some code and found an implementation using a cursor, which made me feel dirty. Here’s an alternative which avoids such nastiness:


DECLARE @ret NVARCHAR(however big we are returning)

SELECT @ret = COALESCE(@ret, '') + ColumnName + ','
FROM TableName
WHERE whatever...

SET @ret = LEFT(@ret, LEN(@ret) - 1)

SELECT @ret

There's only one thing wrong with the 'cleaner' solution: It seems to be slower than a cursor-based version, based on some tests on real data. A loop using the cursor version needs only about 70% of the time used by the 'clean' version - tested using 8 rows.

No comments