我需要从C#程序中执行一大套SQL语句(创建一堆表,视图和存储过程)。
这些语句需要用GO语句分隔,但是SqlCommand.ExecuteNonQuery()不喜欢GO语句。我想提供参考的解决方案是将SQL字符串拆分为几GO行,然后分别执行每个批处理。
GO
SqlCommand.ExecuteNonQuery()
有没有更简单/更好的方法?
使用了解GO分隔符的SQL Server管理对象(SMO)。在这里查看我的博客文章:http: _//weblogs.asp.net/jongalloway/Handling-2200_GO_2200-Separators-in-SQL- Scripts- 2D00_ -the-easy- way
样例代码:
public static void Main() { string scriptDirectory = "c:\\temp\\sqltest\\"; string sqlConnectionString = "Integrated Security=SSPI;" + "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)"; DirectoryInfo di = new DirectoryInfo(scriptDirectory); FileInfo[] rgFiles = di.GetFiles("*.sql"); foreach (FileInfo fi in rgFiles) { FileInfo fileInfo = new FileInfo(fi.FullName); string script = fileInfo.OpenText().ReadToEnd(); using (SqlConnection connection = new SqlConnection(sqlConnectionString)) { Server server = new Server(new ServerConnection(connection)); server.ConnectionContext.ExecuteNonQuery(script); } } }
如果那不适合您,请参阅Phil Haack的库来处理该问题:http : //haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go- separators -和.aspx