SQL DateDifference in a where clause

独自空忆成欢 提交于 2019-11-29 09:10:09

问题


I m doing a query as follows:

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

and not working

I m trying to get the data that s not older than 3 days.

SQL server.

How to do this?

DATEDIFF works too slow..


回答1:


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




回答2:


Microsoft's documentation at http://msdn.microsoft.com/en-us/library/aa258269%28v=sql.80%29.aspx suggests that instead of DateTimeNow you should have getdate(). Does it work any better that way?




回答3:


Your query doesn't seem to bad. Another way to tackle it would be:

SELECT * FROM a WHERE a.DateValue > DATEADD(dd,-3,GETDATE())


来源:https://stackoverflow.com/questions/5266643/sql-datedifference-in-a-where-clause

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