Click here to Skip to main content
15,896,154 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi, this is my question:

I execute this query:

SQL
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

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

For example:
SQL
DECLARE @Codes NVARCHAR(MAX) 
SELECT @Codes = COALESCE(@Codes + ', ', '') + Code
FROM MyTable
 
Share this answer
 
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:

SQL
DECLARE @Codes NVARCHAR(MAX) 

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

SELECT @Codes
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900