views:

34

answers:

2

Can someone please explain why this works. Here is the scenerio. I have a stored proc and it starts to run slow. Then I pick a parameter and declare a variable to house its value and in the proc use the declared variable instead of the parameter. The proc will then speed up considerably.

I think it has something to do with the cached plan and statistics, but I am not sure. Is it that statistics get out of date as the database grows and changes so that the cached plan is optimized on a past state of the data which is different from the present state of the data?

thanks.

+4  A: 

What you describe is commonly referred to as parameter sniffing, and it seems to be a SQL Server only issue - never had it on Oracle IME, nor am I aware of the issue on MySQL. The link I gave breaks down the issue well.

Mind that the statistics used by the optimizer aren't sync'd with data changes - you might need to run UPDATE STATISTICS occaissionally too.

OMG Ponies
OMG - thanks for the answer, your link gave me the explanation I was looking for.
MikeMalter
A: 

When you change ddl the stored procedure execution plan is removed from the cache but as OMG Ponies has said the optimizer does not track data changes.

One way to get around the issue is to use With Recompile option and the procedure will be compiled every time you run it. Another possible solution is to run sp_recompile periodically which marks the stored procedure for recompilation.

Giorgi
IIRC recompile also throws out the query plan, guaranteeing a hard parse
OMG Ponies
Giorgi, thanks for taking the time to respond to my question.
MikeMalter