如何使用C#为SQL Server表添加列?

10

如何使用C#为SQL Server表添加列?

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

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

1
问题和答案太明显了。而且一个人只需要运行这样的脚本(向表中添加列)一次。是的,在 SqlClient 命名空间中支持 DDL。 - Alex Kudryashev
@AlexKudryashev:是的,出现了RTM症候群的情况... - code4life
2个回答

24

你应该使用一个命令:


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
DbCommand也实现了IDisposable接口,所以我建议也将其放在using块中。 - TrueWill
1
谢谢。但是上面的代码缺少了: command.Connection = connection; - Mike108
你如何检查查询是否正确执行?因为executeNonQuery返回-1。 - aseman arabsorkhi

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

有趣的是,SqlCommand和DBCommand是不同的。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接