简体   繁体   English

比较SQL中的生效日期

[英]Comparing effective dates in SQL

Wondering if there is a better why in the WHERE clause of choosing records when you need to look at effective start and end dates? 想知道为什么在需要查看有效的开始日期和结束日期的WHERE子句中选择记录更好?

Currently this how I've done it in the past on MS SQL Server. 目前,这就是我过去在MS SQL Server上所做的方式。 Just worried about the date and not the time. 只是担心日期而不是时间。 I'm using SQL Server 2005. 我正在使用SQL Server 2005。

AND Convert(datetime, Convert(char(10), ep.EffectiveStartDate, 101))
   <= Convert(datetime, Convert(char(10), GetDate(), 101))
AND Convert(datetime, Convert(char(10), ep.EffectiveEndDate, 101))
   >= Convert(datetime, Convert(char(10), GetDate(), 101))

That is terrible, take a look at Only In A Database Can You Get 1000% + Improvement By Changing A Few Lines Of Code to see how you can optimize this since that is not sargable 太糟糕了,看看“ 仅在数据库中您可以通过更改几行代码获得1000%+的改进”,以了解如何优化此代码 ,因为这是不可靠的

Also check out Get Datetime Without Time and Query Optimizations With Dates 还要签出不带时间的获取日期时间带日期的查询优化

@Darren Kopp - you can use @Darren Kopp-您可以使用

set @date2 = '20201001'

this will let you lose the cast. 这会让你失去演员。

footndale - you can use date arithmetic to remove the time as well. footndale-您也可以使用日期算术删除时间。 Something like 就像是

select dateadd(d, datediff(d, 0, CURRENT_TIMESTAMP), 0)

to get today's date (without the time). 获取今天的日期(无时间)。 I believe this is more efficient than casting back and forth. 我相信这比来回转换更有效。

@Darren Kopp @达伦·科普

Be carefull with BETWEEN, check out How Does Between Work With Dates In SQL Server? 注意BETWEEN,请查看SQL Server之间的日期之间如何工作?

AND DateDiff(Day, 0, GetDate()) + 1 > ep.EffectiveStartDate
AND DateDiff(Day, 0, GetDate()) < ep.EffectiveEndDate

I think you will find that these conditions offer the best performance possible. 我认为您会发现这些条件可以提供最佳性能。 This will happily utilize indexes. 这将愉快地利用索引。

I am also very sure that this is right and will give the right data. 我也非常确定这是正确的,并将提供正确的数据。 No further calculation of dates without time portions is needed. 没有时间部分的日期无需进一步计算。

try 尝试

ep.EffectiveStartDate BETWEEN @date1 AND @date2

where you would do something like 你会在哪里做类似的事情

declare @date1 datetime, @date2 datetime;  
set @date1 = cast('10/1/2000' as datetime)  
set @date2 = cast('10/1/2020' as datetime)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM