标签:
Parameter sniffing是Sql Server 创建存储过程的执行计划时,根据传入的参数进行预估生成执行计划的一个功能,通俗的说,就是根据第一个参数为stored procedure生成执行计划,但是Stored Procedure的第一个参数产生的执行计划并不一定是最优的,当后续传参时重用执行计划时,原有的执行计划无法高效响应本次查询,导致查询性能低效。
对于参数嗅探导致的问题,可以使用重新编辑stored procedure,或使用optimize for hint来避免。
Optimize for 查询hint的用法是:使用该提示(在查询优化阶段)生成最佳的执行计划,但是(在查询执行阶段)不适用该值进行查询。
例如以下语句
declare @ID int set @ID=567 select * from dbo.dt_test where id>@ID option(OPTIMIZE for(@ID=541))
Sql Server在查询优化阶段,使用@ID=541来生成执行计划,但是当查询执行阶段,使用@ID=567来作为查询的条件来获取结果集。
如果不适用 optimize for 查询hint,sql server 使用@ID-567来生成执行计划,使用@ID=567来作为查询条件来获取结果集。
MSDN 对Query hint的解释:
OPTIMIZE FOR ( @variable_name { UNKNOWN | = literal_constant } [ , ...n ] )
Instructs the query optimizer to use a particular value for a local variable when the query is compiled and optimized. The value is used only during query optimization, and not during query execution.
OPTIMIZE FOR can counteract the default parameter detection behavior of the optimizer or can be used when you create plan guides. For more information, see Recompile a Stored Procedure.
OPTIMIZE FOR UNKNOWN
Instructs the query optimizer to use statistical data instead of the initial values for all local variables when the query is compiled and optimized, including parameters created with forced parameterization.
If OPTIMIZE FOR @variable_name = literal_constant and OPTIMIZE FOR UNKNOWN are used in the same query hint, the query optimizer will use the literal_constant that is specified for a specific value and UNKNOWN for the remaining variable values. The values are used only during query optimization, and not during query execution.
参考文章:
http://www.dotblogs.com.tw/ricochen/archive/2012/04/23/71725.aspx
https://msdn.microsoft.com/en-us/library/ms181714(SQL.100).aspx
Sql Server Parameter Sniffing 和 optimize for 介绍
标签:
原文地址:http://www.cnblogs.com/ljhdo/p/4882973.html