views:

191

answers:

3

I have to pull a list of integer IDs from a table using only records that match some criteria. For example:

Select ProdID From Products Where (ProdType='XYZ');

The catch is that I have to return it as a set of comma separated values so I can use it to select items in a multi-select list:

111,231,554,112

rather than as records. I do not want to do this in my C# code - I'd like it to come right out of the database via a query this way. Any ideas?

+1  A: 

For SQL server see here: Concatenate Values From Multiple Rows Into One Column

SQLMenace
+2  A: 

MySQL


SELECT GROUP_CONCAT(t.prodid SEPARATOR ',')
  FROM PRODUCTS t
 WHERE t.prodtype = 'XYZ'

Oracle:


There is an excellent summary of the available string aggregation techniques on Tim Hall's site.

SQL Server 2005+


SELECT STUFF((SELECT ','+ t.prodid
                FROM PRODUCTS t
               WHERE t.prodtype = 'XYZ'
             FOR XML PATH('')), 1, 1, '')
OMG Ponies
@OMG Ponies - For the SQLServer case do you know if a method using coalese: select @ids = coalesce(@ids + ',', '') + convert(varchar, id) from ids would be significantly slower than your method?
David Hall
Answering my own question, Rob Farley has a post addressing this http://msmvps.com/blogs/robfarley/archive/2007/04/08/coalesce-is-not-the-answer-to-string-concatentation-in-t-sql.aspx
David Hall
@David Hall: Using the `COALESCE` requires you to declare the variable first - `STUFF` doesn't. Will performance compare tomorrow if I can.
OMG Ponies
+1 - I should have mentioned that this is SQL Server 2008 - sorry!
Mark Brittingham
Ponies - I'd like to see that comparison! I gave Justin the answer as it was the first one with Coalesce and I *will* be doing this in a stored procedure. Still, I'd love to see the results of your analysis.
Mark Brittingham
+1  A: 

In addition to @OMG Ponies method, you could also try this COALESCE trick from:

Using COALESCE to Build Comma-Delimited Strings

declare @string nvarchar(255)

select @string = coalesce(@string + ', ', '') + cast(prodid as nvarchar(5))
from products
Justin Niessner
Good read: http://msmvps.com/blogs/robfarley/archive/2007/04/08/coalesce-is-not-the-answer-to-string-concatentation-in-t-sql.aspx
OMG Ponies
+1 - I should have mentioned that this is SQL Server 2008.
Mark Brittingham
@OMG Ponies - Thanks for the read. Good to know that there's a more reliable way to build the sting.
Justin Niessner
Neat. I've only ever had to do this the other direction, where someone has decided it's a good idea to store a list of comma-separated values in the database.I wonder though if there's any particular benefit in doing this in SQL over array manipulation on the client?
Duncan