Search code examples
c#sql-serversql-server-2005sql-server-2005-express

SQL Server: Could not find prepared statement with handle x


Recently our QA team reported a very interesting bug in one of our applications. Our application is a C# .Net 3.5 SP1 based application interacting with a SQL Server 2005 Express Edition database.

By design the application is developed to detect database offline scenarios and if so to wait until the database is online (by retrying to connect in a timely manner) and once online, reconnect and resume functionality.

What our QA team did was, while the application is retrieving a bulk of data from the database, stop the database server, wait for a while and restart the database. Once the database restarts the application reconnects to the database without any issues but it started to continuously report the exception "Could not find prepared statement with handle x" (x is some number).

Our application is using prepared statements and it is already designed to call the Prepare() method again on all the SqlCommand objects when the application reconnects to the database. For example,

At application startup,

    SqlCommand _commandA = connection.CreateCommand();
    _commandA.CommandText = @"SELECT COMPANYNAME FROM TBCOMPANY WHERE ID = @ID";
    _commandA.CommandType = CommandType.Text;
    SqlParameter _paramA = _commandA.CreateParameter();
    _paramA.ParameterName = "@ID";
    _paramA.SqlDbType = SqlDbType.Int;
    _paramA.Direction = ParameterDirection.Input;
    _paramA.Size = 0;
    _commandA.Parameters.Add(_paramA);
    _commandA.Prepare();

After that we use ExceuteReader() on this _commandA with different @ID parameter values in each cycle of the application.

Once the application detects the database going offline and coming back online, upon reconnect to the database the application only executes,

    _commandA.Prepare();

Two more strange things we noticed. 1. The above situation on happens with CommandType.Text type commands in the code. Our application also uses the same exact logic to invoke stored procedures but we never get this issue with stored procedures. 2. Up to now we were unable to reproduce this issue no matter how many different ways we try it in the Debug mode in Visual Studio.

Thanks in advance..


Solution

  • I think with almost 3 days of asking the question and close to 20 views of the question and 1 answer, I have to conclude that this is not a scenario that we can handle in the way we have tried with SQL server.

    The best way to mitigate this issue in your application is to re-create the SqlCommand object instance again once the application detects that the database is online.

    We did the change in our application and our QA team is happy about this modification since it provided the best (or maybe the only) fix for the issue they reported.

    A final thanks to everyone who viewed and answered the question.