SQL: Dynamic Variable Names

后端 未结 3 729
闹比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.

提交回复
热议问题