简体   繁体   English

如何执行ALTER TABLE查询?

[英]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. 我有一个名为tbl的SQL表,我试图向其中添加列A,B和C。

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: 但是,当我尝试添加多个列时,它不起作用,这给我一个错误..用于添加多个列的命令im编写如下:

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

the debugger highlights the line : cmd.ExecuteNonQuery(); 调试器突出显示以下行: cmd.ExecuteNonQuery(); and throws the following exception: 并引发以下异常:

Exception Details: System.Data.SqlClient.SqlException: Incorrect syntax near '('. 异常详细信息:System.Data.SqlClient.SqlException:'('附近的语法不正确。

Get rid of the parentheses you've added in the ADD clause. 摆脱掉您在ADD子句中添加的括号。 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 指定一次ADD ,然后用逗号分隔列表

如果要与SQL Server数据库进行交互(使用T-SQL),则即使添加多个列,也不能在列定义列表的周围加上括号:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM