“Between” operator generating bad query plan when using parameters

非 Y 不嫁゛ 提交于 2019-12-05 18:17:20

The query plan is based on the parameter values when you first run the query. This is called parameter sniffing. When you add option (recompile), a new plan is generated for each execution.

A query plan is cached based on the hash of the SQL query. So there's a different cache slot for both versions of your query.

Adding option (recompile) is a good solution. You could also use:

option (optimize for (@startdate = '20130128', @enddate = '20130129'));

To generate a query plan as if those values had been passed in.

For testing, you can remove all plans from the cache with:

DBCC FREEPROCCACHE

The problem is likely due to parameter sniffing, a technique designed to optimise the query plan based on the parameters that you pass in first time.

I've had bad experiences with parameter sniffing with date parameters in the past - There is clearly a chance with parameter sniffing that the values initially entered for the query are not representative of typical use of the query (resulting in a query plan optimised for non-typical values), however with date parameters in particular I've often found that the resulting query plan is in fact very inefficient for all values supplied. I have no idea why this is however disabling parameter sniffing generally fixes it.

You can prevent SQL Server from parameter sniffing by using OPTIMIZE FOR UNKNOWN (I've never used this so can't guarentee that it works), or alternatively copying parameters into local variables seems to prevent SQL Server from being able to perform parameter sniffing

-- Perform the query using @StartDateLocal and @EndDateLocal
DECLARE @StartDateLocal DATETIME;
SET @StartDateLocal = @StartDate;

Disabling parameter sniffing in this way is better than forcing a recompile of the query plan each time as compiling a query plan is typically relatively expensive compared to the cost of executing the query unless the query is fairly slow.

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