문제

How can I make my code ignore the error while executing SQL Script file?

If there is an error while executing the sql script file, then I want this method to just ignore it and continue to run the sql script file. Currently, if I put try-catch block inside this method, the error gets caught as an exception and the execution of the SQL script file stops after the error has been caught. I want the execution to continue even if there is an error in the SQL Server.

How can I achieve this?

My code is below.

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();

}
도움이 되었습니까?

해결책

Wrap the ExecuteNonQuery in a try/catch block and leave the catch block empty.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top