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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1351651/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 15:31:20  来源:igfitidea点击:

How to use C# to add a column for a table of sql server?

c#.netsql-server

提问by Mike108

How to use C# to add a column for a table of sql server?

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

For example, I want to execute the following sql in C# code:

比如我想在C#代码中执行下面的sql:

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

采纳答案by Alfred Myers

You should use a Command:

你应该使用一个命令:


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

回答by Jeremiah Stillings

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

Funny how SqlCommand is different then DBCommand

有趣的是 SqlCommand 与 DBCommand 有何不同