What factors should I be aware of that can cause excessive stored procedure recompilation?
Examples of the code that will cause a stored procedure to recompile would
There are a few ways to ensure recompilation of a stored procedure:
WITH RECOMPILE
, exec()
)sp_recompile
. DBCC FREEPROCCACHE
Factors in Recompilation
Besides the hard-factors listed above, what causes stored procedure recompilation? Well, lots of things. Some of these are interwoven with the list above, but I want to re-present them b/c it might not be obvious.
This is by no means an exhaustive list. The query optimizer evolves and suprises no matter how long you've been using SQL Server. But here are some resources that may be of use:
BUT WAIT -THERE'S MORE !
With that said, the presumption in your question is that recompiles are always bad for performance. In fact, often recompliation is good.
So when would you want it to recompile? Let's look at one example of a proc that searches by last name. Stored procedures do 'parameter sniffing' which is a blessing (if it works for you) and a curse (if it works against you). First pass someone searches on Zebr%
for zerbrowski. The last name index realizes this is very specific and will return, lets say, 3 rows from a million -- so one execution plan is built. With the proc compiled for a low row result, the next search is for S%
. Well, S is your most common name and matches 93,543 rows out of 1 million.