执行SQL脚本时忽略错误

时间:2013-05-28 14:56:56

标签: c# sql sql-server sql-scripts

如何在执行SQL Script文件时让代码忽略错误?

如果在执行sql脚本文件时出错,那么我希望此方法只是忽略它并继续运行sql脚本文件。目前,如果我将try-catch块放在此方法中,则会将错误作为异常捕获,并且在捕获错误后SQL脚本文件的执行将停止。即使SQL Server中存在错误,我也希望继续执行。

我怎样才能做到这一点?

我的代码如下。

private void RunSQLScript()
{        
  // file is already defined as a SQL Script file

  string script = file.OpenText().ReadToEnd();

  SqlConnection conn = new SqlConnection(ConnectionString);

  // split script on GO command
  IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);

  conn.Open();

  foreach (string commandString in commandStrings)
  {
    if (commandString.Trim() != "")
       {
          new SqlCommand(commandString, conn).ExecuteNonQuery();
       }
  }

  conn.Close();

}

1 个答案:

答案 0 :(得分:2)

将ExecuteNonQuery包装在try / catch块中,并将catch块留空。