views:

25916

answers:

9

Say you have a table Names that has three rows:

Peter Paul Mary

Is there an easy way to turn this into a single string of "Peter, Paul, Mary"?

A: 

Depends on your database vendor. MySQL has concat_ws. MS SQL Server expects you to do it in your client application.

Update: you could also do it in an external procedure or UDF, perhaps by using a cursor or calling out to CLR code.

Joel Coehoorn
@Joel, the funciton in MySQL is CONCAT_WS(), but it's only useful for 1 row within a result.
Darryl Hein
A: 

One way you could do in ms sql server would be to return the table content as xml (for xml raw), convert the result to a string and then replace the tags with ", "

Manu
+4  A: 

For answers specific to SQL Server, try this question.

Matt Hamilton
A: 

In MySQL there is a funciton GROUP_CONCAT() which allows you to concat the values from multiple rows. Example:

SELECT 1 AS a, GROUP_CONCAT(name ORDER BY name ASC SEPARATOR ', ') AS people 
FROM users 
WHERE id IN (1,2,3) 
GROUP BY a
Darryl Hein
Used to love this one, have not seen a alternative to this function with any other Db yet!
Binoj Antony
+3  A: 

I don't have access to a SQL Server at home, so I'm guess at the syntax here, but it's more or less:

DECLARE @names VARCHAR(500)

SELECT @names = @names + ' ' + Name
FROM Names
Dana
You'd need to init @names to something non-null, otherwise you will get NULL throughout; you'd also need to handle the delimiter (including the unnecessary one)
Marc Gravell
+10  A: 

Use COALESCE:


DECLARE @Names VARCHAR(8000) 
SELECT @Names = COALESCE(@Names + ', ', '') + Name FROM People
Chris Shaffer
To be clear, coalesce has nothing to do with creating the list, it just makes sure that NULL values are not included.
Graeme Perrow
@Graeme Perrow It doesn't exclude NULL values (a WHERE is required for that -- this will *lose results* if one of the input values is NULL), and it *is required in this approach* because: NULL + non-NULL -> NULL and non-NULL + NULL -> NULL; also @Name is NULL by default and, in fact, that property is used as an implicit sentinel here to determine if a ', ' should be added or not.
pst
+1  A: 
DECLARE @Names VARCHAR(8000)
SELECT @name = ''
SELECT @Names = @Names + ',' + Names FROM People
SELECT SUBSTRING(2, @Names, 7998)

This puts the stray comma at the beginning

However, if you need other columns, or to CSV a child table you need to wrap this in scalar UDF

You can use XML path as a correlated subquery in the SELECT clause too (but I'd have to wait until I go back to work because google doesn't do work stuff at home :-)

gbn
+4  A: 

I had a similar issue when I was trying to join two tables with one-to-many relationships. In SQL 2005 I found that XML PATH method can handle the concatenation of the rows very easily.

If there is a table called STUDENTS

SubjectID       StudentName
----------      -------------
1               Mary
1               John
1               Sam
2               Alaina
2               Edward

Result I expected was:

SubjectID       StudentName
----------      -------------
1               Mary, John, Sam
2               Alaina, Edward

I used the following T-SQL:

Select Main.SubjectID,
       Left(Main.Students,Len(Main.Students)-1) As "Students"
From(Select distinct ST2.SubjectID, 
           (Select ST1.StudentName + ',' AS [text()]
            From dbo.Students ST1
            Where ST1.SubjectID = ST2.SubjectID
            ORDER BY ST1.SubjectID
            For XML PATH ('')) [Students]
     From dbo.Students ST2) [Main]
@Ritesh: You saved me a mountain of time with this little gem. Thank you !
Scott Vercuski
A: 

In Sql 20105,

SELECT Stuff((SELECT N', ' + Name FROM Names FOR XML PATH(''),TYPE).value('text()[1]','nvarchar(max)'),1,2,N'')
Steven Chong