Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat many rows into one string in SQL Server 2008? [duplicate]

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?

like image 902
chobo Avatar asked Aug 07 '13 11:08

chobo


People also ask

How can I sum multiple rows with same ID in SQL Server?

To sum rows with same ID, use the GROUP BY HAVING clause.


1 Answers

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
like image 186
Devart Avatar answered Oct 24 '22 10:10

Devart