12

我有许多天变量,我想将其与日期时间列(发送日期)进行比较。

我目前正在这样做:

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

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

任何超过 10 天的内容都应该被删除。我们在 sendDate 列上有索引,但速度仍然慢得多。我知道出于性能原因,左侧不应该进行计算,但是解决此问题的最佳方法是什么?

4

1 回答 1

20

表达方式

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

由于列上的功能,将无法在senddate列 上使用索引senddate

为了使WHERE子句“SARGable”(即能够使用索引),更改为等效条件:

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

[感谢@Krystian Lieber,指出不正确的情况]。

于 2013-01-24T14:59:17.720 回答