I am attempting to set variables whose names are dynamic in a stored procedure:
DECLARE @var01 varchar(50)
DECLARE @var02 varchar(50)
...
DECLARE @var30 varchar(50)
DECLARE @sql = varchar(max)
DECLARE @loopcnter INT
-- (Inside some loop where the loopcounter increments each iteration)
...
SET @sql = 'SET @var0'+CAST(@loopcntr AS Varchar)+'= '''+'somevalue'+''''
-- e.g.) SET @var01= 'somevale'
EXEC (@sql)
This doesn't work because the variables are declared in a different scope to that of the dynamic sql.
What is the correct way to dynamically set variables in this manner?
Well, it is not pretty, but you can do:
if @loopcntr = 1
set var01 = 'somevalue'
else if @loopcntr = 2
set var02 = 'whatever'
else if . . .
This should be sufficiently unpleasant that you might think of alternatives. Oh, here's a good one. Define a table variable and just add rows in for each value:
declare @vars table (
id int identity(1, 1),
loopcntr int,
value varchar(255)
);
. . .
-- inside the loop
insert into @vars(loopcntr, value)
select @loopcntr, 'whatever';
When you want to get a variable, you can do:
declare @var varchar(255);
select @var = value from @vars where loopcntr = <the one I want>;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With