How to Concatenate Column Values from Multiple Rows into a Single Column with SQL Server

Concatenate Column Values from Multiple Rows into a Single Column with SQL Server

I want to concat a field's values from multiple records in a single field. For example:

Name
--------
Joseph
Paul
Mohan

Result should look like:

Names
---------
Joseph, Paul, Mohan

Thanks in advance
LVL 1
K_CH_KrishnaAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Rajkumar GsSoftware EngineerCommented:
This will do

Raj
SELECT   
  NULLIF(  
    STUFF(  
      (SELECT ', ' + Name FROM YourTable FOR XML PATH('') 
                        ), 1, 2, ''  
    ), ''  
  ) AS AllNames

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
krunal_shahCommented:
check this,
USE AdventureWorks
GO
-- Check Table Column
SELECT Name
FROM HumanResources.Shift
GO
-- Get CSV values
SELECT SUBSTRING(
(SELECT ',' + s.Name
FROM HumanResources.Shift s
ORDER BY s.Name
FOR XML PATH('')),2,200000) AS CSV
GO


http://blog.sqlauthority.com/2009/11/25/sql-server-comma-separated-values-csv-from-table-column/
0
K_CH_KrishnaAuthor Commented:
Solution is perfect. It works
0
K_CH_KrishnaAuthor Commented:
How can include where condition here ?
for example if i want to display only names which starts with 'J'
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.