Is there any way to overcome parameter sniffing in SQL Server?

耗尽温柔 提交于 2019-12-01 06:15:10

You can assign the parameters to local variables.

CREATE PROCEDURE SP_NAME

    @param1 INT,
    @param2 INT

AS
DECLARE @local_param1 INT
DECLARE @local_param2 INT

SET @local_param1  = @param1 
SET @local_param2 = @param2 ... 

As explained on this post. Assigning parameters to local variables tells SQL Server to use static densities instead of static histograms, hence avoiding the parameter sniffing problem.

You can apply the option OPTION(OPTIMIZE FOR UNKNOWN) to queries using parameters to have the query optimized to use statistics, rather than being optimized for specific parameters. This bypasses parameter sniffing.

This is explained (summarily) in Query Hints for T-SQL:

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.

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