带有动态列名的SQL插入

时间:2018-04-04 17:34:13

标签: loops sql-server-2014 sql-insert temp-tables

我有一个临时表,其中包含所有列的名称,现在有4个,我循环遍历临时表,并在另一个表中执行插入,现在的问题是我想要的列名称insert取决于它从循环中得到的内容:

以下是代码:

Declare @OutputTable table 
                     (
                         RowID int IDENTITY(1, 1),  
                         ClientID int, 
                         ClientName VarChar(100), 
                         ScoreModule1 VarChar(100), 
                         ScoreModule2 VarChar(100), 
                         ScoreModule3 VarChar(100), 
                         ScoreModule4 VarChar(100)
                     )

Declare @TempModuleNumber table 
                          ( 
                               RowIDNumber int IDENTITY(1, 1), 
                               ModuleNumber varchar (300)
                          )

INSERT INTO @TempModuleNumber(ModuleNumber) 
VALUES ('ScoreModule1'), ('ScoreModule2'),
       ('ScoreModule3'), ('ScoreModule4')

Declare @ModuleRowCountNumber int 
Declare @ModuleCounterNumber int 
Declare @ModuleNumber varchar(300) 

Select @ModuleRowCount = COUNT(@ModuleNumber) 
from @TempModuleNumber

set @ModuleCounterNumber = 1 

while @ModuleCounterNumber <= @ModuleRowCount
begin
    Select @ModuleNumber = ModuleNumber 
    from @TempModuleNumber 
    where RowIDNumber = @ModuleCounterNumber

    Insert into @OutputTable (ClientID, ClientName, @ModuleNumber) --This is where the problem is the @ModuleNumber is. I get a "syntax error". Is there another way of doing this to it depends on what it gets from the Loop?

    Set @ModuleCounterNumber = @ModuleCounterNumber + 1
END

1 个答案:

答案 0 :(得分:1)

我只改变了必要的部分:

while @ModuleCounterNumber <= @ModuleRowCount
begin
    Select @ModuleNumber = ModuleNumber 
    from @TempModuleNumber 
    where RowIDNumber = @ModuleCounterNumber

    DECLARE @SQL VARCHAR(MAX)
    SET @SQL = 
    '
    Insert into @OutputTable (ClientID, ClientName, ' + @ModuleNumber + ')
    SELECT A,B,C  //<----------- THIS IS THE MISSING PART I WAS TALKING ABOUT
    '
    EXEC(@SQL)

    Set @ModuleCounterNumber = @ModuleCounterNumber + 1
END