12

How to concat many rows into one strings?

Query:

SELECT name FROM mytable;

Result:

name
----
kim
lee
park
cho

Just I want.

name
----
kim,lee,park,cho

Impossible?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
chobo
  • 4,830
  • 5
  • 23
  • 36

3 Answers3

46

Try this one -

DECLARE @temp TABLE (name NVARCHAR(50))

INSERT INTO @temp (name)
VALUES ('kim'),('lee'),('park'),('cho')

SELECT STUFF((
    SELECT ',' + name
    FROM @temp
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

Output -

kim,lee,park,cho
Devart
  • 119,203
  • 23
  • 166
  • 186
10

I have been working on something similar this morning, adding the case will also work for 1 returned row. Hope this helps. Else follow the link the first comment sent you.

Declare @NameList VarChar(MAX) = ''    
select @NameList = 
    case when @NameList = ''
        then coalesce(Name, '')
        else @NameList + coalesce(',' + Name, '')
    end
from mytable
print @NameList 

Ben

palota
  • 465
  • 4
  • 8
Ben Barter
  • 159
  • 1
  • 10
8

Try this

 SELECT   
name= substring((SELECT ( ', ' + Name)
                       FROM TableName t
                       FOR XML PATH( '' )
                      ), 3, 1000 )  FROM mytable tn
Amit
  • 15,217
  • 8
  • 46
  • 68