Friday, February 23, 2007

The ADO prepared property.

Today I was playing with some ADO queries and I stumble one more time with the famous prepared property. Based on the BDS help it says:

Description Set Prepared before calling the Open method to specify whether ADO prepares the command used to create the dataset’s recordset. If Prepared is set to true and the dataset component is connected to a data store, ADO prepares the command before executing it. If Prepared is set to false, ADO does not prepare the command. The default value of Prepared is false.

Now, after a bit of research I found this interesting article on the msn dev network.

The important part is here:

Prepared property

In theory, the Prepared property was designed to reduce work on the server by pre-compiling ad hoc queries so subsequent executions would use a temporary stored procedure instead of repeating the compile phase each time the query is executed. However, this is not the case with ADO's implementation—keep reading.

Since ODBC was invented some years ago, SQL Server has gotten much smarter—it now knows how to leverage existing (in cache) compiled query plans. That is, once you execute a query from ADO (or by any means), SQL Server constructs a query plan, saves it in the procedure cache, and executes it. When the query is done, SQL Server marks the query plan as "discardable" but leaves it in memory as long as it can. When another identical (or close-enough) query comes in, which is very likely in systems running multiple clients, SQL Server simply re-uses the cached plan. This saves a significant amount of time and greatly improves scalability. It makes SQL Server actually run faster as more users are added, assuming they're doing about the same things with the same set of queries.

ADO and its ODBC and OLE DB data providers know about this strategy, and in most cases they execute sp_executesql to take advantage of this feature. However, this puts the Prepared property in a quandary. It insists on creating temporary stored procedures, but the data providers insist on using sp_executesql. The result? Chaos. I describe what happens a little later when executing Command objects is discussed.

My recommendation for the Prepared property: forget it—at least for SQL Server. For other providers, set up a trace that shows exactly what's going on—what the server is being asked to do.

Now this is extremely interesting for me, specially the sp_executesql part, DataSnap indeed wraps every call in a "sp_executesql" so we are good there, now about using the prepared property, I will do more research on it, but for now, I will leave it alone. :P



No comments:

A painless self-hosted Git service

Remember how a part of my NAS setup was to host my own Git server? Well that forced me to review options and I stumble into Gitea .  A extr...