Click here to Skip to main content
14,389,999 members
Rate this:
Please Sign up or sign in to vote.
Hi, this is my question:

I execute this query:

SELECT CODE FROM MyTable 


This is the result:

CODE
1
2
5
9

How can I insert the result in a varchar variable?:

@CODES='1,2,5,9'

I thought go row by row with a "FOR" cycle, but I don't know how to do it.

thanks.
Posted
Rate this:
Please Sign up or sign in to vote.

Solution 1

You can actually use COALESCE to do this. If you google for "sql concatenate rows" you get lots of examples:

For example:
DECLARE @Codes NVARCHAR(MAX) 
SELECT @Codes = COALESCE(@Codes + ', ', '') + Code
FROM MyTable
   
Rate this:
Please Sign up or sign in to vote.

Solution 2

Yeaaahhh !!! that's the solution!!! a lot of thanks Ryan. :D

I had to do a little change because "Code" field was declared as integer, I had to convert this field to a Varchar and that's it:

this is my Solution:

DECLARE @Codes NVARCHAR(MAX) 

SELECT @Codes = COALESCE(@Codes + ', ', '') + CONVERT(varchar,Code)
FROM MyTable

SELECT @Codes
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100