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

I would like to combine a field's values from multiple records in a single field. For example:

Last     First     Code
    -------  --------- ----
    Lesand   Danny       1
    Lesand   Danny       2
    Lesand   Danny       3
    Benedi   Eric        7
    Benedi   Eric       14

Result should look like:

    Last     First     Codes
    -------  --------- -----
    Lesand   Danny     1,2,3
    Benedi   Eric       7,14
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:
Just have a try and let me know

Replace 'YourTable' which I gave for table name with your actual table name

Raj
SELECT DISTINCT Last, First, 
  NULLIF(   
    STUFF(   
      (SELECT ',' + Code FROM YourTable WHERE Last = D.Last AND First = D.First FOR XML PATH('')  
                        ), 1, 2, ''   
    ), ''   
  ) AS Codes 
FROM YourTable D

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
halfbloodprinceCommented:
THIS WORKS!!!!:
First Create this function :
Create Function ufnStringValues (@LastName Varchar(50))
Returns Varchar(100)
As Begin
DECLARE @listStr VARCHAR(100)
Select @listStr = COALESCE(@listStr+',' , '') + Code
FROM Test01
Where Last = @LastName
Return @listStr
End

Then use the above function like this:

Select Last,
         First,
         (
                  Select dbo.ufnStringValues(Last)
            ) As Code
From   Test01  
Group By Last,
            First

0
K_CH_KrishnaAuthor Commented:
Wrongly placed
0
Éric MoreauSenior .Net ConsultantCommented:
how did you solved it? by using our ideas?
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.