加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

在Microsoft SQL Server中比较日期的最佳方法是什么?

发布时间:2020-12-13 20:49:57 所属栏目:Windows 来源:网络整理
导读:我在一个非常大的表中有一个SQL datetime字段。它被索引,需要查询。 问题是SQL总是存储时间组件(即使它总是午夜),但搜索是一天,而不是时间。 declare @dateVar datetime = '2013-03-11;select t.[DateColumn]from MyTable twhere t.[DateColumn] = dateVa
我在一个非常大的表中有一个SQL datetime字段。它被索引,需要查询。

问题是SQL总是存储时间组件(即使它总是午夜),但搜索是一天,而不是时间。

declare @dateVar datetime = '2013-03-11;

select t.[DateColumn]
from MyTable t
where t.[DateColumn] = dateVar;

不会返回任何东西,因为t。[DateColumn]总是包含时间分量。

我的问题是这是最好的方法?

似乎有两个主要的选择:

>使用dateadd创建第二个变量,并在…之间使用,或者> = …和…< =。
>将t。[DateColumn]转换为只有日期的组件 – 我认为这将导致任何索引被忽略。

这两个都看起来很混乱 – 我真的不想做一个范围比较或扫描表。

有没有更好的办法?

如果这些选项之一是一贯的最佳方式,那么如何和为什么?

在任何情况下,转换为DATE或使用开放式日期范围将产生最佳性能。 FYI,转换日期使用指数是表现最好的。更多测试不同的技术在文章: What is the most efficient way to trim time from datetime?发表于Aaron Bertrand

从那篇文章:

DECLARE @dateVar datetime = '19700204';

-- Quickest when there is an index on t.[DateColumn],-- because CONVERT can still use the index.
SELECT t.[DateColumn]
FROM MyTable t
WHERE = CONVERT(DATE,t.[DateColumn]) = CONVERT(DATE,@dateVar);

-- Quicker when there is no index on t.[DateColumn]
DECLARE @dateEnd datetime = DATEADD(DAY,1,@dateVar);
SELECT t.[DateColumn] 
FROM MyTable t
WHERE t.[DateColumn] >= @dateVar AND 
      t.[DateColumn] < @dateEnd;

也是从那篇文章:使用BETWEEN,DATEDIFF或CONVERT(CHAR(8)…都慢了。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读