How to jump back into a Try Catch after a Query Timeout occurs?

Alvord, Timothy 236 Reputation points
2023-02-01T17:32:43.16+00:00

Our servers are notoriously slow executing SQL Queries, especially at the end of each month. I have the following Try .. Catch:

Obviously it will not compile because the label is out of scope. Is there ANY way to return back to the line that cause the Timeout Error? Usually, the Server executes the 2nd try fine.

Try
{

               cmd = new SqlCommand("SELECT DISTINCT [Order Number] FROM OPERATIONS_BY_WORKCENTER WHERE LTRIM(RTRIM([Item   Number 2nd Kit])) = '" + sPartNumber + "'", myConnection2);
RetryQuery:    dr = cmd.ExecuteReader();

}
catch (Exception ex)

{
    if( ex.Message.ToUpper().Contains("Timeout")) goto RetryQuery;
}



C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,979 questions
0 comments No comments
{count} votes

Accepted answer
  1. Bruce (SqlWork.com) 52,826 Reputation points
    2023-02-01T17:46:05.5133333+00:00

    use a while loop

    var success = false;
    while (!success)
    {
       try
       {
          cmd = new SqlCommand("SELECT DISTINCT [Order Number] FROM OPERATIONS_BY_WORKCENTER WHERE LTRIM(RTRIM([Item   Number 2nd Kit])) = '" + sPartNumber + "'", myConnection2);
          dr = cmd.ExecuteReader();
          success = true;
       }
       catch (Exception ex)
       {
          if (!ex.Message.ToUpper().Contains("Timeout")) throw ex;
       }
    }
    

    you can also use the polly library:

    http://www.thepollyproject.org

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful