Why such a huge difference in performance if I put my dates in WHERE clause (first query) or if I put same dates as a parameters (second query)
--------/* Execution time 3 sec*/
select
tblNoteDiaries.DueDate,
col2,
col3
from MyTable
where CAST(tblNoteDiaries.DueDate as date) <= cast(getdate()as date) and cast( tblNoteDiaries.DueDate as date) >= CAST('2017-09-29' as DATE)
--------/* Execution time 10 sec*/
declare @DateFrom datetime = '2017-09-29',
@DateTo datetime = '2017-10-05'
select
tblNoteDiaries.DueDate,
col2,
col3
from MyTable
where CAST(tblNoteDiaries.DueDate as date) >= @DateFrom and cast( tblNoteDiaries.DueDate as date) <= @DateTo
I need this query as a stored procedure, what would be the best approach to utilize date parameters without degrading performance??
2条答案
按热度按时间kyvafyod1#
I simulated on my database using below queries
and checked execution plan. it was 48% for first query and 52% for the second one.
Then I added
option(recompile)
to the second query and then both took exact the same percentageSo as Nick, said, it is parameter sniffing.
You can get rid of parameter sniffing using updated statistics or using
RECOMPILE
option for your queries and stored procedures.nlejzf6q2#
因为你的变量声明为
datetime
,它有更高的数据类型优先级,所以你要显式地将你的DueDate
列转换为date
,然后再转换为datetime
。对变量使用
date
,您应该看到相同的性能。更好的是,如果类型已经正确,不要对日期列使用CAST
。