1

I have created a stored procedure which creates a table at runtime. The table columns and their data types for this dynamic table comes from another table already in place in database.

I am calling this stored procedure from C# console application code. The stored procedure is throwing a syntax error and I am totally not able to figure out what is causing this syntax error.

This is the stored procedure code I've written:

CREATE procedure [dbo].[sproc_TableExists]
   @TableName NVARCHAR(128) 
      ,@Column1Name NVARCHAR(32)
      ,@Column1DataType NVARCHAR(32)
      ,@Column1Nullable NVARCHAR(32)
AS
   DECLARE @SQLString NVARCHAR(MAX)
   BEGIN
       IF( EXISTS (select * from INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = @TableName))
       BEGIN
            SET @SQLString = 'ALTER TABLE ' + @TableName + '( '+ @Column1Name + ' ' + @Column1DataType + ' '+ @Column1Nullable +')'
            EXEC (@SQLString)
        END
    ELSE
        BEGIN
            SET @SQLString = 'CREATE TABLE ' + @TableName + '( '+ @Column1Name + ' ' + @Column1DataType + ' '+ @Column1Nullable +')'
            EXEC (@SQLString)
        END
END
GO

Error I am getting calling it from code :

Incorrect syntax near '('.

2 Answers 2

2

The problem lies in the following line of code, when altering an existing table:

SET @SQLString = 'ALTER TABLE ' + @TableName + '( '+ @Column1Name + ' ' + @Column1DataType + ' '+ @Column1Nullable +')'

This generates the following output (as an example using a fake table\column name):

ALTER TABLE TableEx( ColumnEx NVARCHAR(MAX) NULL)

However, this is not a valid SQL statement.

If you want the behaviour to be to add a new column when the table already exists, use this instead:

SET @SQLString = 'ALTER TABLE ' + @TableName + ' ADD '+ @Column1Name + ' ' + @Column1DataType + ' '+ @Column1Nullable

Which will produce the output:

ALTER TABLE TableEx ADD ColumnEx NVARCHAR(MAX) NULL

Note that if your intention is to change the name of a pre-existing column in a pre-existing table you will need to test for this separately - the above only adds a new column to an existing table.

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

1 Comment

Thanks for your response @Martin. It solved it. What a stupid SQL mistake i was doing. Thanks again.
1

Replace EXEC (@SQLString)

with EXEC @SQLString

2 Comments

This causes the production of another error Could not find stored procedure 'ALTER TABLE TableEx ADD ColumnEx NVARCHAR(MAX) NULL'.
Thanks @Aishvarya. But that line never seemed a problem as I tested running CREATE statement separately with that EXEC line working absolutely fine.

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.