PeacefulSoul
PeacefulSoul

Reputation: 33

How to execute an ALTER TABLE query?

I have an SQL table called tbl, im trying to add the columns A, B and C to it.

When i execute the command :

String addcolumns = "ALTER TABLE SqlCreatedTbl ADD  A char(50) ;";
                        ......
             cmd = new SqlCommand(addcolumns, conn);
             conn.Open();
             cmd.ExecuteNonQuery();

The column is added !

However, when i try to add multiple columns, it does NOT work, it gives me an error.. the command im writting for adding multiple columns is the following:

addcolumns = "ALTER TABLE SqlCreatedTbl ADD  ( A char(50),  B char(50), C char(50) );";

the debugger highlights the line : cmd.ExecuteNonQuery(); and throws the following exception:

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near '('.

Upvotes: 2

Views: 9449

Answers (2)

BoltClock
BoltClock

Reputation: 723538

If you're interacting with an SQL Server database (using T-SQL), you must not place parentheses around your list of column definitions even when adding multiple columns:

ALTER TABLE SqlCreatedTbl ADD A char(50), B char(50), C char(50);

Upvotes: 2

Rebecca Chernoff
Rebecca Chernoff

Reputation: 22605

Get rid of the parentheses you've added in the ADD clause. You don't have them in the single column version, and you don't need them with multiple columns either. Specify ADD once and then just comma-separate your list

Upvotes: 4

Related Questions