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

时间:2009-08-29 15:04:37

标签: c# .net sql-server

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

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

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

2 个答案:

答案 0 :(得分:19)

您应该使用命令:


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

答案 1 :(得分:2)

SqlCommand cmd2 = new SqlCommand();
// create columns for healed
cmd2 = new SqlCommand("ALTER TABLE TotalHeals ADD "+Healee+" INT", openCon);
cmd2.ExecuteNonQuery();

有趣的是SqlCommand与DBCommand不同