30.06.2013 Views

SQL Server Execution Plans - Red Gate Software

SQL Server Execution Plans - Red Gate Software

SQL Server Execution Plans - Red Gate Software

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 5: Controlling <strong>Execution</strong> <strong>Plans</strong> with Hints<br />

though, a certain value, or subset of values, supplied to the parameters results in an<br />

execution plan that performs extremely poorly. This is the parameter sniffing problem.<br />

Parameter sniffing is a process that occurs with all stored procedures; it is normally at the<br />

very least benign, and often very beneficial to the performance of the system. As values<br />

are passed to a stored procedure or parameterized query, the optimizer uses those values<br />

to evaluate how well an index will satisfy the query requirements, based on the available<br />

statistics. In most cases, this produces more accurate execution plans.<br />

However, situations can arise whereby the data distribution of a particular table or index<br />

is such that most parameters will result in a good plan, but some parameters can result in<br />

a bad one. Problems occur when the first execution of the parameterized query or stored<br />

procedure happens to use a very non-representative parameter value. The resulting plan<br />

will be stored in cache and reused, and often turns out to be highly inefficient for the<br />

parameter values that are more representative. Alternatively, a "good" plan may be aged<br />

out of the cache, or recompiled due to changes in the statistics or the code, and replaced<br />

with a "bad" plan. As such, it becomes, to a degree, a gamble as to where and when the<br />

problematic execution plan is the one that is created and cached.<br />

In <strong>SQL</strong> <strong>Server</strong> 2000, only two options are available:<br />

1. Recompile the plan every time, using the RECOMPILE hint.<br />

2. Get a good plan and keep it, using the KEEPFIXED PLAN hint.<br />

Both of these solutions (covered later in this chapter) could create as many problems as<br />

they solve since, depending on its complexity and size, the RECOMPILE of the query could<br />

be longer than the execution itself. The KEEPFIXED PLAN hint could be applied to the<br />

problematic values as well as the useful ones.<br />

In <strong>SQL</strong> <strong>Server</strong> 2005 and above, when you're hitting a bad parameter sniffing situation,<br />

you can use the OPTIMIZE FOR hint. This hint allows you to instruct the optimizer to<br />

optimize the query for the value that you supply, rather than the value passed to the<br />

200

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!