【问题标题】:Executing SQL scripts with GO statements without SMO使用没有 SMO 的 GO 语句执行 SQL 脚本
【发布时间】:2012-06-13 13:04:32
【问题描述】:

我遇到的一个问题是将应用程序部署到没有安装 SMO 的机器上。我想执行具有GOstatements 的脚本,但也想避免在目标机器上安装 SMO 包或解析 SQL 脚本文件的需要(因为我不知道 sql 脚本是否包含函数或 SP)。

我尝试手动将 SMO relevenat dll 复制到可执行文件的 bin 文件夹,但运行应用程序总是需要一些其他 dll。

有什么帮助吗?

【问题讨论】:

  • 您需要提供更多关于您正在尝试做什么、预期结果和具体问题的详细信息。
  • 为什么要使用 GO 语句?
  • 我有 MSSQL 脚本需要执行,但不知道它们的格式,必须支持执行包含 GO 语句的脚本
  • GO 只是分割脚本的指标。为什么不获取查询文本,将其拆分为您选择的数组或集合,以GO 作为分隔符,然后依次迭代运行每个脚本?

标签: c# sql-server database smo


【解决方案1】:

除了 SMO,sqlcmd 实用程序可以理解 GO 语句。您需要使用 System.Diagnostics.Process 才能将您的脚本作为参数调用它。

我绝不是说这是 方法,但它是一种有效的替代方法。如果目标计算机上不存在该实用程序,您仍然会遇到与以前相同的问题。

您也可以使用安装程序包部署 SMO,而无需在目标计算机上“安装”它:

Embedding SMO dlls in Setup and deployment

【讨论】:

    【解决方案2】:

    我发现以下解决方案经过良好测试

    using (SqlConnection cn = new SqlConnection(connectionString))
      {
        try
        {
          cn.Open();
          FileInfo file = new FileInfo(fileName);
          string script = file.OpenText().ReadToEnd();
          string[] splitChar = { "\r\nGO\r\n" };
          var sqlLines = script.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);
          int res = 0;
          SqlCommand cmd = null;
          foreach (var query in sqlLines)
          {
              cmd = new SqlCommand(query, cn)
              {
                  CommandTimeout = 5400
              };
              res = cmd.ExecuteNonQuery();
          }
          cn.Close();
        }
        catch (Exception ex)
        {
          msg = ex.Message;
        }
        finally
        {
          cn.Close();
        }
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-05
      • 2013-09-06
      相关资源
      最近更新 更多