Stored procedures and OPTIMIZE FOR UNKNOWN

こ雲淡風輕ζ 提交于 2019-11-30 10:23:02

The default behaviour of the SQL compiler is to use the values of any parameters given in the first execution of an SP to help optimise the plan (see paragraphs 2 and 3 of this MSDN article on SP recompilation). That plan is then cached for re-use until it leaves the cache - lots of detail on the plan caching process here.

The MSDN blog you cite is noting ways to make this process easier for the compiler; I think item 4 (quoted in the question) is suggesting that this is an advantage of stored procedures over ad-hoc SQL.

The OPTIMIZE FOR UNKNOWN hint instructs the compiler to aviod the default behaviour; that it should ignore the parameter values given in the first execution and select a more generalised plan. This is a more extreme version of item 2 in the list of suggestions at the end of the blog post cited in the question;

2 If you find that the optimizer is picking different plans over time that have varying performance characteristics, consider using a parameter hint with a representative “average” value to get a good, common query plan that will work reasonably for all values.

but rather than selecting an average or representative value, the compiler will effectively ignore the parameter values entirely.

Consider using OPTIMIZE FOR UNKNOWN in the circumstances given quoted in item 2 - when the same query gives very variable performance because the plan is poor in some circumstances - typically when parameters in the query filter columns of very variable cardinality.

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