Click here to Skip to main content
15,891,253 members
Articles / Database Development / SQL Server / SQL Server 2008
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
4.96/5 (22 votes)
8 Mar 2012CPOL 262.7K   18   14
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)


Written By
Web Developer Mahindra Logisoft Business Solution Limited, Chenn
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 5 Pin
Sk. Tajbir4-Feb-13 22:31
Sk. Tajbir4-Feb-13 22:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.