1

Here is my table:

 CODE     __NAME
 1000     ___AB
 1001     ___CA
 1001     ___DR
 1001     ___LVN
 1100     ___ER
 1110     ___WL

What I want to get to is:

 CODE___NAME
 1000  ___AB
 1001  ___CA,DR,LVN
 1100  ___ER
 1110  ___WL

I know I can use looping to accomplish this but I was wondering if there might be a better way. Thanks

marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
user142253
  • 484
  • 1
  • 6
  • 16

1 Answers1

2

Try something like this, this will get you what you want.

   Select 
        Main.CODE,
        Left(Main.Names,Len(Main.Names)-1) As Names
    From
        (
        Select distinct T2.CODE, 
        (
         Select 
            RTRIM(T1.NAME) + ', ' AS [text()]
         From   
            Test T1
         Where
            T1.CODE = T2.CODE
         ORDER BY 
            T1.CODE
         For XML PATH ('')
        ) [Names]
        From Test T2
        ) [Main]
Richard.Gale
  • 1,807
  • 5
  • 25
  • 45