SQL: Dynamic Variable Names

后端 未结 3 728
闹比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:45

    Since you are saying in comments that you are assigning the set of variables merely to insert the assigned values into a table, you could use an approach avoiding the variables altogether. You could insert all the values into a temporary table or table variable, providing them with numeric indices, then pivot the column of values and insert the resulting row into the target table. So, something like this:

    DECLARE @values TABLE (Ind int IDENTITY(1,1), Value varchar(50));
    
    INSERT INTO @values
    SELECT ...
    ;
    
    INSERT INTO TargetTable (Col1, Col2, ..., Col30)
    SELECT [1], [2], ..., [30]
    FROM @values
    PIVOT (
      MAX(Value) FOR Ind IN ([1], [2], ..., [30])
    ) AS p
    ;

    I even suspect there might also be a possibility to do everything in such a way as to avoid the cursor you are mentioning in comments.

    0 讨论(0)
  • 2021-01-07 01:51

    You can also use stored procedure sp_executesql which allows passing parameters. Although I recommend to use additional table to store variables.

    0 讨论(0)
  • 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 = <the one I want>;
    
    0 讨论(0)
提交回复
热议问题