Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Dynamic Variable Names

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?

like image 893
Jamie Stuart Robin Parsons Avatar asked Sep 01 '26 18:09

Jamie Stuart Robin Parsons


1 Answers

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>;
like image 117
Gordon Linoff Avatar answered Sep 04 '26 08:09

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!