How to turn one column of a table into a csv string in SQL Server without using a cursor
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
STRING_AGG was added in sql 2017
https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql?view=sql-server-2017
SELECT STRING_AGG (ColumnName, ',') AS csv
FROM TableName
GROUP BY ColumnName2
without the trailing comma version:
declare @s varchar(max);
select @s = isnull(@s + ', ' + lastname, lastname)
from person
order by lastname;
print @s;