MicBehrens
MicBehrens

Reputation: 1798

adding a column with variable name

I am trying to dynamically add som columns to 2 tables if they dont already exist. My problem is, that the name of the column depends on another column's value.

But apparently the following is not allowed, why?

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

I get the following errors

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 + '.

Upvotes: 1

Views: 5173

Answers (1)

Sean
Sean

Reputation: 15144

Look at this:

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

The third line is just not right, at best it should be:

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

However, even that is not going to work. You're probably better off creating the whole DDL statement as a string, and then executing that. Something like:

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

Upvotes: 1

Related Questions