Friday, February 24, 2012

Add column with variable name

HI!

Im trying to use an stored procedure to add a new column.
The problem is that the column name is stored in a variable, and I get syntax error.

Here is my code:

CREATE PROCEDURE test AS
declare @.colname as varchar(10)

set @.colname = 'new_col'

alter table prueba add @.colname int

And here is the error I get:
Error 170: Line 6 Incorrect syntax near '@.colname'

Any idea?Originally posted by soy_lore_lore
HI!

Im trying to use an stored procedure to add a new column.
The problem is that the column name is stored in a variable, and I get syntax error.

Here is my code:

CREATE PROCEDURE test AS
declare @.colname as varchar(10)

set @.colname = 'new_col'

alter table prueba add @.colname int

And here is the error I get:
Error 170: Line 6 Incorrect syntax near '@.colname'

Any idea?

Try this:

exec('alter table prueba add '+@.colname+' int')|||Originally posted by snail
Try this:

exec('alter table prueba add '+@.colname+' int')

THANKS!

No comments:

Post a Comment