T-SQL – Concatenate many rows into a single text string

How to concatenate many rows into a single text string?
It’s easier than you think!

Let’s say that my table might look like this:

Names:
James
Daniel
Cindy
Edward

Now, I want to combine the values of ‘Name’ into a single string (separated by a comma: ‘, ‘)

“James, Daniel, Cindy, Edward”

You might want to use a query similar to this one:

DECLARE @Names VARCHAR(MAX)
SELECT @Names = COALESCE(@Names + ', ', '') + Name FROM People
SELECT @Names



MultiValue()
Want to split it up into separate values again? 🙂
Use this table-valued function (TVF) to do that:
Multi-value parameter function








Advertisements

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