SQL: Dynamic Variable Names

后端 未结 3 745
闹比i
闹比i 2021-01-07 01:34

I am attempting to set variables whose names are dynamic in a stored procedure:

DECLARE @var01 varchar(50)  
DECLARE @var02 varchar(50) 
...
DECLARE @var30 v         


        
3条回答
  •  独厮守ぢ
    2021-01-07 01:52

    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 = ;
    

提交回复
热议问题