Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用C#为sql server的表添加列?_C#_.net_Sql Server - Fatal编程技术网

如何使用C#为sql server的表添加列?

如何使用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

如何使用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 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();