2012-07-02 4 views
0

이미 존재하지 않는다면 동적으로 두 테이블에 열을 추가하려고합니다. 내 문제는 열의 이름이 다른 열의 값에 달려 있다는 것입니다.변수 이름이있는 열을 추가하십시오.

분명히 다음은 허용되지 않습니다. 이유가 무엇입니까?

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; 

그러나, 심지어 그것은 wor에 가지 않을 것입니다. 케이. 전체 DDL 문을 문자열로 만든 다음 실행하는 것이 좋습니다. 다음과 같음 :

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