SQL DateDifference in a where clause

后端 未结 3 1653
耶瑟儿~
耶瑟儿~ 2020-12-28 19:16

I m doing a query as follows:

SELECT
  *
FROM a
WHERE DATEDIFF(D, a.DateValue, DateTimeNow) < 3;

3条回答
  •  天涯浪人
    2020-12-28 19:44

    DateDiff is extremely fast... Your problem is you are running it on the database table column value, so the query processor must run the function on every row in the table, even if there was an index on this column. This means it has to load the entire table from disk.

    Instead, use the dateAdd function on todays date, and compare the database table column to the result of that single calculation. Now it only runs DateAdd() once, and it can use an index (if one exists), to only load the rows that match the predicate criterion.

    Where a.DateValue > DateAdd(day,-3,getdate())

    doing this in this way makes your query predicate SARG-able

提交回复
热议问题