4

i have this table

Cream
----------
CHOCALATE
GREEN
TEST

want out put in select query like this

cream

CHOCALATE,GREEN,TEST

Natrium
  • 30,772
  • 17
  • 59
  • 73
Yagnesh84
  • 157
  • 1
  • 4
  • 19
  • Yeah it looks like most of the questions you asked have been answered satisfactory, so just select an answer.. – Colin Sep 28 '09 at 17:56

4 Answers4

6

With sysobjects this worked:

DECLARE @List varchar(2000)

SELECT @List = COALESCE(@List + ',', '') + Cast(name As varchar(50))
FROM sys.sysobjects

SELECT @List As 'List'
Arthur
  • 7,939
  • 3
  • 29
  • 46
  • brilliant, simply brilliant. I have always went down the aggregate UDF path before but this solution relies on sequential evaluation of the variable expressions! – Andriy Volkov Sep 28 '09 at 18:05
4

I found a useful resource here when I needed to do this, but as the others said, use COALESCE...

DECLARE @List VARCHAR(1000)

SELECT @List = COALESCE(@List + ', ', '') + Name
FROM Cream

SELECT @List
Jane
  • 1,953
  • 1
  • 20
  • 27
3

You can use coalesce

Adriaan Stander
  • 162,879
  • 31
  • 289
  • 284
0

The best way to do this, is to create an aggregate user defined function and register it on the database.

Try here for an example.

http://msdn.microsoft.com/en-us/library/ms165055.aspx

Your query would look like "SELECT dbo.Concatenate(Field) FROM Cream"

You will be returned what you expect "a,b,c,d..." ect.

mrwayne
  • 627
  • 6
  • 15