如何使用C#为sql server的表添加列?
如何使用C#为sql server的表添加列 例如,我想在C代码中执行以下sql:如何使用C#为sql server的表添加列?,c#,.net,sql-server,C#,.net,Sql Server,如何使用C#为sql server的表添加列 例如,我想在C代码中执行以下sql: 您应该使用以下命令: using (DbConnection connection = new SqlConnection("Your connection string")) { connection.Open(); using (DbCommand command = new SqlCommand("alter table [Product] add [ProductId] int defa
您应该使用以下命令:
using (DbConnection connection = new SqlConnection("Your connection string")) {
connection.Open();
using (DbCommand command = new SqlCommand("alter table [Product] add [ProductId] int default 0 NOT NULL")) {
command.Connection = connection;
command.ExecuteNonQuery();
}
}
有趣的是,SqlCommand与DBCommand不同,DBCommand也实现了IDisposable,所以我建议把它也放在using块中。谢谢。但是上面的代码遗漏了:command.Connection=Connection;问题和答案太明显了。此外,还可以只运行一次这样的脚本(将列添加到表中)。是的,DDL在
SqlClient
名称空间中受支持。@AlexKudryashev:是的,RTM的一个案例正在发生。。。
using (DbConnection connection = new SqlConnection("Your connection string")) {
connection.Open();
using (DbCommand command = new SqlCommand("alter table [Product] add [ProductId] int default 0 NOT NULL")) {
command.Connection = connection;
command.ExecuteNonQuery();
}
}
SqlCommand cmd2 = new SqlCommand();
// create columns for healed
cmd2 = new SqlCommand("ALTER TABLE TotalHeals ADD "+Healee+" INT", openCon);
cmd2.ExecuteNonQuery();