Random timeout running a stored proc - drop recreate fixes

帅比萌擦擦* 提交于 2019-12-01 20:45:00

This sounds very much like a problem I've seen time and time again - where the stored procedure plan has been flushed from the plan cache and the next time the procedure is run it just so happens that the parameters passed in result in a plan that is probably great for that set of parameters but which performs awfully for other combinations.

If you've 'optional' parameters - where NULL or a value may be passed through, and you're using OR in the WHERE clause to cope with this then that's usually going to lead to this sort of thing.

WITH RECOMPILE may result in a lot of CPU going to compiling the plan each time - if the stored procedure is called a lot then this could easily have an effect on the general performance of your server - whether this os outweighed by the effect of a bad plan is another matter.

In general, it's better to try to rewrite the query - if you are using ORs to cope with diffferent sets of parameters then dynamic SQL (done the right way, using sp_executesql with parameters) can help a lot.

P.S. Regarding the stored procedure working fine when you run it - I've seen this too - I expect that it's down to getting a different plan generated - my suspicion has always been that running through e.g. SSMS has a slightly different set of SET options enabled than (in my instance) .Net - and the plans are cached separately in this instance. If anyone can validate that this may happen it'd be appreciated!

I would doubt that it is the stored procedure that is directly causing this, unless it is performing some kind of locking/transaction logic that is not being cleaned up. Even then, I cant see how dropping/recreating would have any affect on this. I would probably look at the data the SP is using and attempt to trace the execution path of this using profiling and see if the performance can be improved.

This is most probably a result of an bad execution plan stored for the specific proc.

The problem (simplified) is that SQL server tries to optimize the usage of execution plans based on the parameters passed. This can then lead to horrendous performance in some cases.

Heres some reading to explain it further.

http://blogs.msdn.com/b/queryoptteam/archive/2006/03/31/565991.aspx
http://elegantcode.com/2008/05/17/sql-parameter-sniffing-and-what-to-do-about-it/

On the bright side, its very simple to fix by copying the passed parameters in the proc to local variables.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!