Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 concatenate local variable

Author  Topic 

actuary
Starting Member

23 Posts

Posted - 2008-06-17 : 06:10:33
Hi guys,

I have a cursor that loops over a table and I use a local variable to append the column data. However when I try to print this variable, it comes as empty!

The code is

declare @testVar varchar(max)
<cursor loop begins>
set @testVar = @testVar + ',' + @SomeColName
<cursor loop ends>

print 'Value: ' + @testVar

I can't understand why the @testVar is empty, since the @SomeColName has a value in every iteration.

Thanks!

Abu-Dina
Posting Yak Master

206 Posts

Posted - 2008-06-17 : 06:12:32
I wouldn't use a cursor but to answer your question, try initialisiung the variable, something like
set @testVar =''
after you declare it
Go to Top of Page

actuary
Starting Member

23 Posts

Posted - 2008-06-17 : 06:15:25
Aaah... works great now! Simple mistake :)

Thanks!
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-06-17 : 09:12:01

Are you trying to cocatenate values from a single column, Instead of cursor, do



declare @testVar varchar(max)
SELECT @testVar = coalesce(@testVar+',','')+ SomeColName from your_table
print 'Value: ' + @testVar


Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -