all groups > sql server programming > may 2006 >
You're in the

sql server programming

group:

Variable appending


Variable appending ybc
5/28/2006 9:31:02 PM
sql server programming:
Hi,
I'd like to know how to append strings to a varible, ie. @var = @var + @string

The code is something like this:

while (@@fetch_status = 0)
begin
set @message = @message + @user + ';'
fetch next from user_curs into @user
end

print @user

It seems string appending doesn't work.

Thanks,

RE: Variable appending Omnibuzz
5/28/2006 9:54:02 PM
Hi ybc,
Two things.
1. Initailise @messagebefore the loop
set @message = ''

while (@@fetch_status = 0)
.....
....
....

2. And if @user is not of type varchar, then use
set @message = @message + cast(@user as varchar)+ ';'

I think its the first one you are missing :)
Hope this helps


[quoted text, click to view]
RE: Variable appending Omnibuzz
5/28/2006 10:07:01 PM
Also, the user might have been null in one of the rows.

So use this..
while (@@fetch_status = 0)
begin
set @message = @message + isnull(@user,'') + ';'
fetch next from user_curs into @user
end

Re: Variable appending Tony Rogerson
5/29/2006 12:00:00 AM
If you are using SQL Server 2005 you don't need to do this in a cursor
anymore.

I talk through an example on my blog:
http://sqlblogcasts.com/blogs/tonyrogerson/archive/2006/05/11/429.aspx.

It's basically using the FOR XML....

create table mailing_list (
individual_name nvarchar(100) not null,
list_name nvarchar(10) not null
)

insert mailing_list ( individual_name, list_name ) values( 'tony r', 'List
A' )
insert mailing_list ( individual_name, list_name ) values( 'tony r', 'List
B' )
insert mailing_list ( individual_name, list_name ) values( 'tony r', 'List
C' )
insert mailing_list ( individual_name, list_name ) values( 'joe r', 'List
A' )
insert mailing_list ( individual_name, list_name ) values( 'joe r', 'List
B' )
insert mailing_list ( individual_name, list_name ) values( 'alex r', 'List
A' )

select distinct
individual_name,
list = substring(
( select ', ' + list_name as [text()]
from mailing_list m2
where m2.individual_name = m1.individual_name
for xml path(''), elements )
, 3, 100 )
from mailing_list m1

Gives this result :-

alex r List A
joe r List A, List B
tony r List A, List B, List C

Tony.

--
Tony Rogerson
SQL Server MVP
http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a SQL
Server Consultant
http://sqlserverfaq.com - free video tutorials


[quoted text, click to view]

RE: Variable appending ybc
5/29/2006 12:19:01 AM
Hi Omnibuzz,
The "Initailise @messagebefore the loop " woks,
Thanks,
ybc

[quoted text, click to view]
Re: Variable appending Madhivanan
5/29/2006 7:06:03 AM
AddThis Social Bookmark Button