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?

2

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

An explanation of how this works would be helpful for future visitors.
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

Comments

8

Try this

 SELECT   
name= substring((SELECT ( ', ' + Name)
                       FROM TableName t
                       FOR XML PATH( '' )
                      ), 3, 1000 )  FROM mytable tn

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.