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 2000 Forums
 Transact-SQL (2000)
 set varirable = to exec sql statement?

Author  Topic 

robg69
Starting Member

41 Posts

Posted - 2003-12-22 : 11:31:41
Hey guys/gals,
Can you set a variable to hold the results of a dynamic sql statement?
I can do it with a normal sql statement:

declare @val varchar(10)
select @val = @val + desc from table1


BUT does anyone know how to do this dynamically? The following example didn't seem to work:

(Assume @num is an integer from a loop)...

declare @val varchar(10)
select @val = @val + exec('select val' + @num + ' from table1')

Thanks!

nr
SQLTeam MVY

12543 Posts

Posted - 2003-12-22 : 12:00:20
declare @sql nvarchar(1000), @val int
select @sql = 'select @val = val' + @num + ' from table1'
exec sp_executesql @sql, N'@val int out', @val out

see
http://www.nigelrivett.net/sp_executeSQL.html

==========================================
Cursors are useful if you don't know sql.
DTS can be used in a similar way.
Beer is not cold and it isn't fizzy.
Go to Top of Page

robg69
Starting Member

41 Posts

Posted - 2003-12-22 : 12:08:53
I just came across sp_executesql and was messing around with it. That script is exactly what I was looking for.

Thanks nr!
Go to Top of Page
   

- Advertisement -