Datediff performance

笑着哭i 提交于 2019-11-29 13:49:57

问题


I have a number of days variable which I want to compare against a datetime column (senddate) .

Im currently doing this :

DECLARE @RunDate datetime = '2013-01-01' 
DECALRE @CalculationInterval int = 10

DELETE
FROM TableA
WHERE datediff(dd, senddate, @RunDate) > @CalculationInterval 

So basically anything that is older then 10 days should get deleted, we have Index on sendDate column but still the speed is much slower, I know the left side should not have calculation for performance reasons, but what is the optimal way of otherwise solving this issue?


回答1:


The expression

WHERE datediff(dd, senddate, @RunDate) > @CalculationInterval 

won't be able to use an index on the senddate column, because of the function on the LHS on senddate

In order to make the WHERE clause 'SARGable' (i.e. able to use an index), change to the equivalent condition:

WHERE senddate < dateadd(dd, -@CalculationInterval, @RunDate)

[Thanks to @Krystian Lieber, for pointing out incorrect condition ].



来源:https://stackoverflow.com/questions/14504189/datediff-performance

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