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

前端之家收集整理的这篇文章主要介绍了在Microsoft SQL Server中比较日期的最佳方法是什么?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在一个非常大的表中有一个sql datetime字段。它被索引,需要查询

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

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

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

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

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

似乎有两个主要的选择:

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

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

有没有更好的办法?

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

@H_301_21@
在任何情况下,转换为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)…都慢了。

原文链接:https://www.f2er.com/windows/372299.html

猜你在找的Windows相关文章