Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server / SQL-Server-2008

Concatenate many rows into a single text string using SQL Server 2008

4.96/5 (22 votes)
8 Mar 2012CPOL 264.5K  
Using COALESCE function - concatenate many rows into a single text string output in SQL Server.

The following code is used to concatenate many rows into a single text string with comma separated using SQL Server COALESCE function.

My table format is like this:

Name
RAM
GURU
Sundar
Shyam
Inba
Kalai

I need output like this:

"RAM, GURU, Sundar, Shyam, Inba, Kalai"

I use the following query:

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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)