views:

793

answers:

2

I want to return the results of select Column from Table into a comma separated string using SQL Server.

The column in question is rather large (nvarchar(2000)) so the solution has to be able to handle very large result values.

+5  A: 
DECLARE @result nvarchar(max)
SET @result = ''

SELECT @result = @result + [Column] + N','
FROM [TABLE]

//TODO: trim last ',' if you require

PRINT @result

If Column can be null, then either exclude it first, or use ISNULL/COALESCE - otherwise a single NULL will break the entire sequence. It is more efficient to exclude it with a WHERE:

SELECT @result = @result + [Column] + N','
FROM [TABLE]
WHERE [Column] IS NOT NULL
Marc Gravell
works as advertised. thanks. for those who may find this later, it's easy to knock off the last comma: `select @result = substring(@result, 1, (LEN(@result)-1))`
Kyle West
Just watch out for the zero-length case...
Marc Gravell
SELECT @result = COALESCE(@result + N', ', N'') + [Column]will avoid the last comma without perf penalty.
Robert Jeppesen
+2  A: 

without the trailing comma version:

declare @s varchar(max);

select @s = isnull(@s + ', ' + lastname, lastname)
from person
order by lastname;

print @s;
Michael Buen
I'd expect that to use a few more CPU cycles, though... personally, if I needed to trim it, I'd use the string functions instead.
Marc Gravell
MSSQL strings are immutable, I'd expect that copying big strings(trimming would also yield a copy) would also incur some CPU cycles, I'm not sure though. I think if it is a one-off thing, micro-optimizations aren't warranted.
Michael Buen