Using COALESCE function to make values separated with commas

DECLARE @List VARCHAR(8000)

SELECT @List = COALESCE(@List + ',', '') + CAST(OfferID AS VARCHAR)
FROM   Emp
WHERE  EmpID = 23

SELECT @List 

This approach to aggregate concatenation is not guaranteed to work. If you are on at least SQL Server 2005 XML PATH or CLR aggregates are preferred.

The definitive article on the subject is Concatenating Row Values in Transact-SQL

Leave a Comment