如何使用c#运行sql server脚本?

如何使用c#运行sql server脚本?,c#,sql-server,C#,Sql Server,我正在为运行sql server脚本编写以下代码: string sqlConnectionString = "Data Source=.;Initial Catalog=behzad;Integrated Security=True"; //string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True"; FileInfo file = new

我正在为运行sql server脚本编写以下代码:

string sqlConnectionString = "Data Source=.;Initial Catalog=behzad;Integrated Security=True";
//string sqlConnectionString = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=True";
FileInfo file = new FileInfo("d:\\behzadBULK.sql");
string script = file.OpenText().ReadToEnd();
SqlConnection conn = new SqlConnection(sqlConnectionString);
Microsoft.SqlServer.Server server = new Microsoft.SqlServer.Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);

但是这句话:

Microsoft.SqlServer.Server server = new Microsoft.SqlServer.Server(new ServerConnection(conn));
我得到这个错误:

 Are you missing reference?


应该向项目中添加什么引用?

您这里的问题是缺少对程序集
Microsoft.SqlServer.Server
的引用,这就是出现错误的原因

您可以通过在项目上单击鼠标右键,然后单击“添加引用”,为特定程序集的项目添加引用来解决此问题。这将打开一个窗口,向您显示所有可用的程序集,您可以从中选择此程序集并将其添加到项目中

在这之后,确保您已经在代码中为它添加了名称空间,并且应该这样做


希望这有帮助。

尝试使用SQLclient连接,而不是SqlServer

using System.Data;
using System.Data.SqlClient;
还有一些像这样的代码

settings = System.Configuration.ConfigurationManager.ConnectionStrings["MyTweetConnection"];
ConnectionString = settings.ConnectionString;
SQLCon = new SqlConnection(ConnectionString);

使用
使用System.Data.SqlClient见我使用System.Data.SqlClient添加的这个;但是,站起来吧!它在错误中显示了什么引用?只要在项目中安装对
Microsoft.SqlServer.Server
的引用,如果它现在不存在的话。并在代码中为其添加名称空间,这应该可以做到