views:

619

answers:

3

I need a similar function to Oracle WM_CONCAT in SQL Server, which returns a comma separated list of whatever field you pass it as argument. For example, in Oracle,

select WM_CONCAT(first_name) from employee where state='CA'

returns "John, Jim, Bob".

How can I do this in SQL Server?

Thanks

A: 

AFAIK, you need to do it by yourself.

You could build an user defined function that loop with a cursor the records of Employee where the state is CA and returns the concatenation of their names.

eKek0
No, no need to use a CURSOR at all.
gbn
+1  A: 

The actual answer:

SELECT
   SUBSTRING(buzz, 2, 2000000000)
FROM
    (
    SELECT 
        firstname
    FROM 
        employee
    WHERE
        State = 'CA'
    FOR XML PATH (',')
    ) fizz(buzz)

A common question here. Some searches:

gbn
Worth noting this is only valid for SQL Server 2005 and later. OP hasn't stated which version of SQL Server they're using.
Chris J
You can replace the SUBSTRING, with the STUFF command which will function properly without needing to know the string length.
WesleyJohnson
@Chris J: I would say that SQL 2k5 is a reasonable assumption that 10 years after SQL 2000 RTM and 2.5 versions later
gbn
@WesleyJohnson: length of 2 billion which covers every conceivable string...
gbn
+1  A: 

Try this:


    drop table #mike_temp 
go

select * into #mike_temp 
  from (select 'Ken'  as firstname, 'CO' as state
         union all
        select 'Mike' as firstname, 'CO' as state
         union all
        select 'Tom' as firstname , 'WY' as state
       ) a
go

SELECT distinct 
       state
      ,STUFF((SELECT ', ' + b.firstname FROM #mike_temp b where a.state = b.state FOR XML PATH('')),1, 2, '') AS CSVColumn
  from #mike_temp a