Home > C#, Programming, SQL > Force SQL Command Timeout and catch it

Force SQL Command Timeout and catch it

September 8th, 2009 Leave a comment Go to comments

Sometimes you want to catch and specially handle an SQL-Timeout.
To do this, just put a try-catch around your SQL-Call and catch the SqlException. Now check the Property Number if it is -2 (which stands for Timeout). That’s it.

Here’s a little Code Example how that could look like:

try
{
	RunSomeSqlQuery();
}
catch (SqlException ex)
{
	// Check if it's a TimeoutException
	if (ex.Number == -2)
	{
		// It is...
		// Do whatever you need
	}
	else
	{
		// Other Type of Exception, re-throw it or whatever
		throw;
	}
}

If you want to simulate a Timeout in your SQL-Statement, just use the WAITFOR DELAY SQL-Statement to block for some Time and therefore results in a Timeout.

Here’s an example to wait for 1 Minute:

WAITFOR DELAY '00:01:00'
Ad
Categories: C#, Programming, SQL Tags:
  1. Gail Bowen
    September 14th, 2012 at 11:41 | #1

    Thank you – this was very helpful.

  1. No trackbacks yet.
*