一个where子句中的SQL DateDifference [英] SQL DateDifference in a where clause

查看:215
本文介绍了一个where子句中的SQL DateDifference的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做一个查询如下:

select * from a
 where DATEDIFF(d, a.DateValue , DateTimeNow) <3;

而不工作

获取不超过3天的数据。

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

SQL服务器。

如何做?

DATEDIFF工作太慢..

DATEDIFF works too slow..

推荐答案

DateDiff 非常快...您的问题是您正在数据库表列值上运行它,因此查询处理器必须在表中的每一行运行该函数,即使有该列的索引。这意味着它必须从磁盘加载整个表。

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.

而是在今天的日期使用 dateAdd 函数,并将数据库表列与该单个结果进行比较计算。现在它只运行 DateAdd()一次,它可以使用索引(如果存在),只加载与谓词标准匹配的行。

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.

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

以这种方式使您的查询谓词 SARG-capable

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

这篇关于一个where子句中的SQL DateDifference的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆