Asked By Erland Sommarskog
14-Jan-08 06:12 PM

bean (dbvann@product-key.com) writes:
Look at the procedure again:
create procedure Search
@FirstName varchar (20) = NULL,
@LastName varchar (40) = NULL,
@State char (2) = NULL
as
select *
from authors
where (@FirstName IS NULL or au_fname = @FirstName)
and (@LastName IS NULL or au_lname = @LastName)
and (@State IS NULL or state = @State)
SQL Server builds the query plan for the procedure when it's first
executed and puts the plan in cache. The query plan must work for all input.
Say that on the first call, the user specifies @FirstName and there
is an index on that column. What if the optimizer uses that index, and
the next user asks about state? How useful is the index on au_fname in
this case?
If you add the option WITH RECOMPILE to the procedure definition or
the EXEC statement, there will be a new plan each time. Ah, but in
this case, it could use the index? No. The optimizer does not perform
any flow analysis, so it does not know what the values of the parameters
will be at run time. So again, it must scan the table to ensure a
correct result.
In SQL 2005, there is also an statement-level hint OPTION(RECOMPILE)
which forces statement recompilation each time. Now, with this option
in force, the optimizer should really be able to use the indexes, right?
Nothing will be put in the cache, and the variables cannot change values
during the query. That is perfectly correct, but there still is a snag:
the SQL Server developers apparently overlooked this possibility, and
uses the same optimisation scheme as for a procedure with parameters.
I submitted an item on Connect some time back, and it was closed as
Postponed. As still works the same in the most recent CTP of SQL 2008,
I just reopened it.
https://connect.microsoft.com/SQLServer/feedback/ViewFeedback.aspx?FeedbackID=244298
--
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/prodtechnol/sql/2005/downloads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodinfo/previousversions/books.mspx