Concatenation across rows

A fun read for today: Not-so-dirty hacks reminds me of the good old methods of doing concatenation across rows.

The list we want to concatenate are in:

SELECT productname
FROM Production.Products AS P
ORDER BY productid;

And this is what I’d do to generate a comma delimited string of “productname” in the order of “productid”:

DECLARE @String NVARCHAR(max);
SELECT @String = COALESCE(@String + N’, ‘, N”) + productname
FROM Production.Products AS P
ORDER BY productid;
SELECT @String;

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s