Ad hoc query processing

When Adaptive Server caches a statement, it changes the statement from an ad-hoc query to a lightweight stored procedure. For example, if you issue sp_bindefault or sp_bindrule in the same batch as the statement that invokes the default or rule without caching the statement, Adaptive Server issues error message 540. However, if you cache the statement, Adaptive Server binds the default or rule to the column.

Adaptive Server may issue a runtime errors instead of normalization errors when statements are cached and executed as stored procedures. For example, this query raises error number 241 if the statement is not cached, but raises a Truncation error and aborts the command if the statement is cached.

create table t1(c1 numeric(5,2)
go
insert t1 values(3.123)
go

To process ad hoc SQL statements using the statement cache:

  1. Adaptive Server parses the statement.

    If the statement should be cached (see “Caching conditions”), Adaptive Server computes a hash value from the statement. Adaptive Server uses this hash value to search for a matching statement in the statement cache (see “Statement matching criteria”).

  2. Adaptive Server caches the SQL statement text.

  3. Adaptive Server wraps the SQL statement with a lightweight stored procedure and changes any local variables into procedure parameters. The internal representation of the lightweight procedure is not yet compiled into the plan.

  4. Adaptive Server converts the SQL statement into an execute statement for the corresponding lightweight procedure.

  5. Adaptive Server then executes the procedure. Substituting the lightweight procedure increments the @@nestlevel global variable.


Statement matching criteria

Adaptive Server matches an ad hoc SQL statement to a cached statement by the SQL text and by login (particularly if both users have sa_role), user ID, database ID, and session state settings. The relevant session state consists of settings for these set command parameters:

Settings for these parameters determine the behavior of the plan Adaptive Server produces for a cached statement. See the Reference Manual: Commands.

NoteYou must configure set chained on/off in its own batch if you enable the statement cache.


Caching conditions

Adaptive Server caches statements according to these conditions:


Statement cache sizing

Each cached statement requires approximately 1K memory in the statement cache, depending on the length of the SQL text. Each cached plan requires at least 2K of memory in the procedure cache. To estimate the statement cache memory required, account for the following for each statement to be cached: