2012-07-02 57 views
0

我想動態添加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

啊,我的不好。編輯:) – Behrens

+1

有列名稱取決於表值幾乎肯定是壞規範化充其量 – Ghost

回答

0

看看這個:

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) 
相關問題