Skip to content
Advertisement

Incorrect syntax and exceptions thrown when trying to add a column pragmatically with c#

I’m having trouble with exceptions being thrown with the following syntax:

SqlCommand cmd = new SqlCommand(
    "ALTER TABLE [dbo].[User Groups] ADD " + ColumnName + " VARCHAR(20) NOT NULL", 
    connection
);

Error says its an error somewhere near VARCHAR. Can’t work out what the issue is, please someone enlighten me: 🙂

Advertisement

Answer

Wrap the column name in square brackets:

SqlCommand cmd = new SqlCommand(
    "ALTER TABLE [dbo].[User Groups] ADD [" + ColumnName + "] VARCHAR(20) NOT NULL", 
    connection
);
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement