3

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

}

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. Worked. Such a simple thing and I was putting try-catch on the entire method instead of just the ExecuteNonQuery part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.