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.

3 Answers 3

13

Try this:

declare @sql nvarchar(100)

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

exec sp_executesql @sql

Sign up to request clarification or add additional context in comments.

Comments

3

Try

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

Comments

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.