【问题标题】:How to use C# to add a column for a table of sql server?如何使用 C# 为 sql server 的表添加列?
【发布时间】:2009-08-29 15:04:37
【问题描述】:

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

例如我想在C#代码中执行如下sql:

alter table [Product] add 
[ProductId] int default 0 NOT NULL

【问题讨论】:

  • 问题和答案太明显了。另外一个人可以只运行一次这样的脚本(将列添加到表中)。是的,SqlClient 命名空间支持 DDL。
  • @AlexKudryashev:是的,RTM-itis 正在发生……

标签: c# .net sql-server


【解决方案1】:

你应该使用命令:


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();
    }
}

【讨论】:

  • DbCommand 也实现了 IDisposable,所以我建议也将它放在 using 块中。
  • 谢谢。但是上面的代码漏掉了:command.Connection = connection;
【解决方案2】:
SqlCommand cmd2 = new SqlCommand();
// create columns for healed
cmd2 = new SqlCommand("ALTER TABLE TotalHeals ADD "+Healee+" INT", openCon);
cmd2.ExecuteNonQuery();

有趣的是 SqlCommand 与 DBCommand 有何不同

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    相关资源
    最近更新 更多