执行大型 SQL 脚本(使用 GO 命令) [英] Execute a large SQL script (with GO commands)

查看:47
本文介绍了执行大型 SQL 脚本(使用 GO 命令)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 C# 程序中执行大量 SQL 语句(创建一堆表、视图和存储过程).

I need to execute a large set of SQL statements (creating a bunch of tables, views and stored procedures) from within a C# program.

这些语句需要用GO语句分隔,但是SqlCommand.ExecuteNonQuery()不像GO语句.我想我将发布以供参考的解决方案是在 GO 行上拆分 SQL 字符串,并分别执行每个批处理.

These statements need to be separated by GO statements, but SqlCommand.ExecuteNonQuery() does not like GO statements. My solution, which I suppose I'll post for reference, was to split the SQL string on GO lines, and execute each batch separately.

有更简单/更好的方法吗?

Is there an easier/better way?

推荐答案

使用理解 GO 分隔符的 SQL Server 管理对象 (SMO).在此处查看我的博客文章:http://weblogs.asp.net/jongalloway/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts-2D00-the-easy-way

Use SQL Server Management Objects (SMO) which understands GO separators. See my blog post here: 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-and.aspx

If that won't work for you, see Phil Haack's library which handles that: http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators-and.aspx

这篇关于执行大型 SQL 脚本(使用 GO 命令)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆