I'm not sure if this is possible, but I need to create a set of variables dynamically within a WHILE loop. For example, if the loop needs to execute 5 times, it would create 5 new variables named @var1, @var2, etc... then set each one to a given value. If I use EXEC, the variable is only assigned within the scope of that batch and nowhere else. I'm not very familiar with sp_executesql, but I could not get it to work either. My initial code looked like this.
This errors out as var1 is only in the scope of the exec batch (at least I'm assuming that's how it works). Is there a way to do something like this where the dynamically created variable would be accessible globally?
Code:
declare @loopcount int
declare @stmt varchar(1000)
set @loopcount = 1
WHILE @loopcount <= 5
BEGIN
set @stmt = 'declare var' + cast(@loopcount as varchar(1)) + ' varchar(100) set @var' + cast(@loopcount as varchar(1)) + ' = ' + @loopcount
exec (@stmt)
END
print @var1
This errors out as var1 is only in the scope of the exec batch (at least I'm assuming that's how it works). Is there a way to do something like this where the dynamically created variable would be accessible globally?