4
DECLARE @result varchar(MAX)

SELECT 
  NAME
FROM
  Table
WHERE
  ID = @Id

I need to fill @result with result Names, separated by ','.
For example, if SELECT returns 'A','B' and 'C', the @result should be 'A, B, C'.
It is Microsoft SQL Server 2008.

Sergey Metlov
  • 25,747
  • 28
  • 93
  • 153
  • possible duplicate of [Creating a long string from a result set](http://stackoverflow.com/questions/295575/creating-a-long-string-from-a-result-set) – codingbadger Jun 15 '11 at 13:39

4 Answers4

13
DECLARE @result varchar(MAX)
SET @result = '';

SELECT 
  @result = @result + NAME + ','
FROM
  Table
WHERE
  ID = @Id

SET @result = SUBSTRING(@result, 1, LEN(@result) - 1)

SELECT @result

Enjoy :D

The Evil Greebo
  • 7,013
  • 3
  • 28
  • 55
1
DECLARE @CSV varchar(max)

SET @CSV = ''

SELECT @CSV = @CSV + Col1 + ',' FROM Table WHERE ...

SET @CSV = LEFT(@CSV, LEN(@CSV) -1)

PRINT @CSV
Lasse Edsvik
  • 9,070
  • 16
  • 73
  • 109
1

Try this

declare @result varchar(max)

select @result = COALESCE(@result + ', ', '') + name
from table
Ash Burlaczenko
  • 24,778
  • 15
  • 68
  • 99
0

DECLARE @Contribution AS VARCHAR(MAX) SET @Contribution = ( SELECT RTRIM(Ltrim(C.strname)) + '; ' FROM tbl M INNER JOIN tbl2 ON tbl2.ID =tbl.CID WHERE M.PID =@PID ORDER BY C.Orderby FOR XML PATH('') )

Print @Contribution

Raj Jayaswal
  • 468
  • 1
  • 9
  • 22