添加具有变量名称的列

时间:2012-07-02 17:37:34

标签: sql sql-server-2008 tsql

我试图动态地将som列添加到2个表中,如果它们不存在的话。 我的问题是,列的名称取决于另一列的值。

但显然以下是不允许的,为什么?

declare @inputs int; 
set @inputs = (select inputs from campaigns where id = 102) + 1; 
update campaigns set inputs = @inputs where id = 102; 
if col_length('campaigns', 'input' + @inputs) is null alter table campaigns add input' + @inputs + ' ntext null; 
if col_length('campaigns', 'input' + @inputs + 'text') is null alter table campaigns add input' + @inputs + 'ivocall ntext null; 
if col_length('rapports', 'input' + @inputs) is null alter table rapports add input' + @inputs + ' ntext null; 
if col_length('rapports', 'input' + @inputs + 'values') is null alter table rapports add input' + @inputs + 'values ntext null; 
update campaigns set input' + @inputs + ' = '1||test||||0||0||0||0||0||2||0' where id = 102

我收到以下错误

Msg 102, Level 15, State 1, Line 4
Incorrect syntax near ' + @inputs + '.
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near ' + @inputs + '.
Msg 102, Level 15, State 1, Line 6
Incorrect syntax near ' + @inputs + '.
Msg 102, Level 15, State 1, Line 7
Incorrect syntax near ' + @inputs + '.
Msg 102, Level 15, State 1, Line 8
Incorrect syntax near ' + @inputs + '.

1 个答案:

答案 0 :(得分:1)

看看这个:

if col_length('campaigns', 'input' + @inputs) is null 
    alter table campaigns 
    add input' + @inputs + ' ntext null; 

第三行是不对的,充其量应该是:

if col_length('campaigns', 'input' + @inputs) is null 
    alter table campaigns 
    add 'input' + @inputs ntext null; 

然而,即使这样也行不通。您可能最好将整个DDL语句创建为字符串,然后执行它。类似的东西:

set @sql = 'alter table campaigns add column input' + @inputs + ' ntext null'
exec (@sql)