Click here to Skip to main content
Click here to Skip to main content

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

, 8 Mar 2012
Rate this:
Please Sign up or sign in to vote.
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:

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)

Share

About the Author

Ramanujam Shankar
Web Developer Mahindra Logisoft Business Solution Limited, Chenn
India India
No Biography provided

Comments and Discussions

 
QuestionTo avoid the ", " at the beginning of the string PinmemberMember 1016856530-Sep-13 23:47 
This is a function I have created to select either a company name or a firstname/lastName depending on the contact type. A second case statement ensures that the string does not start with ", "
 
ALTER FUNCTION [dbo].[CDGetAllNames](@ID INT)
RETURNS NVARCHAR(MAX)
AS
BEGIN
declare @names nvarchar(max)
set @names = '';
select @names =
case when ct.ContactTypeId = 4 then
CASE WHEN LEN(@names)=0 Then
ct.Companyname
Else
COALESCE(@Names + ', ', '') +ct.Companyname
end
else
CASE WHEN LEN(@names)=0 Then
ct.Firstname + ' ' + ct.Lastname
else
COALESCE(@Names + ', ', '') + ct.Firstname + ' ' + ct.Lastname
end
end
from CDContact ct
where Id = @ID

return @names;

END
QuestionConcerned about the use of COALESCE vs a Case Function Pinmemberdalyteaching23-Aug-13 3:51 
GeneralMy vote of 5 PinmemberSk. Tajbir4-Feb-13 22:31 
Generalc# PinmemberMember 823748321-Dec-12 9:06 
GeneralMy vote of 5 Pinmemberwolfcoder7514-Dec-12 9:53 
QuestionFor both sql server 2005 and 2008 PinmemberShawn02713-Mar-12 2:45 
AnswerRe: For both sql server 2005 and 2008 Pinmemberwolfcoder7514-Dec-12 9:58 
Questionbla bla Pinmembersajithinnate11-Mar-12 20:18 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140821.2 | Last Updated 8 Mar 2012
Article Copyright 2012 by Ramanujam Shankar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid