views:

926

answers:

3

Hi I am writing a large stored procedure, which creates a dynamic report table, of n columns in size, the first 6 are constant the remainder depend on a few arguments passed to the procedure to create the table with the required columns.

The problem that I am having is with the following TSQL

DECLARE @columnname VARCHAR(50)
SET @columnname = 'on_' + @description

IF NOT EXISTS(SELECT * FROM syscolumns WHERE id = OBJECT_ID('reports')
       AND NAME = @columnname)
BEGIN
      ALTER TABLE reports ADD @columnname VARCHAR(50) NULL
END

I am getting syntax errors with this at the @columnname in the ALTER TABLE statement of the above code.

Also as I am new to this, I am not sure if this is the best way to do this, or if there are better ways in TSQL to generate the required dynamic table.

+5  A: 

Try this:

declare @sql nvarchar(100)

set @sql = 'ALTER TABLE reports ADD '+ @columnname+' VARCHAR(50) NULL'

exec sp_executesql @sql

SqlACID
+1  A: 

Cannot get around having to do it dynamically I believe so change your BEGIN block to something like this:

DECLARE @sql VARCHAR(8000)

BEGIN
SET @sql = 'ALTER TABLE Table_1 ADD '+@columnname+' VARCHAR(50) NULL'

    EXEC(@sql)

END

SomeMiscGuy