2009-08-29 59 views
5

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

例如,我想在C#代码来执行下列SQL:

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

问题和答案太明显了。再加上一个可以运行这样的脚本(向列表添加列)一次。是的,'SqlClient'命名空间支持DDL。 – 2016-05-22 01:51:06

+0

@AlexKudryashev:是的,RTM-itis的一个例子是... – code4life 2016-05-22 02:05:56

回答

16

你应该使用命令:


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,所以我建议把它放在一个使用块中。 – TrueWill 2009-08-29 15:26:04

+1

谢谢。但是上面的代码错过了: command.Connection = connection; – Mike108 2009-08-29 15:35:05

+0

@TrueWill,Mike108。你们是对的。 +1为你们两个。 – 2009-08-29 15:37:43

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

滑稽的SqlCommand是如何不同,那么的DbCommand

相关问题