Create varchar from SELECT result

DECLARE @result varchar(MAX) SELECT NAME FROM Table WHERE ID = @Id 

I need to populate @result result Names separated by ",".
For example, if SELECT returns "A", "B" and "C", @result should be "A, B, C".
This is Microsoft SQL Server 2008.

+4
source share
4 answers
 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

+9
source
 DECLARE @CSV varchar(max) SET @CSV = '' SELECT @CSV = @CSV + Col1 + ',' FROM Table WHERE ... SET @CSV = LEFT(@CSV, LEN(@CSV) -1) PRINT @CSV 
+1
source

try it

 declare @result varchar(max) select @result = COALESCE(@result + ', ', '') + name from table 
0
source

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

0
source

All Articles