简体   繁体   English

SQL Server:将日期时间与GETDATE()进行比较

[英]SQL Server: compare datetime day with GETDATE()

I have a stored procedure that should fetch all records with a date equal to the current date or in the future. 我有一个存储过程应该获取日期等于当前日期或将来的所有记录。 The dates are saved in column targetDate and formatted as datetime. 日期保存在列targetDate中,并格式化为datetime。 My corresponding WHERE clause is the following: 我对应的WHERE子句如下:

WHERE A.targetDate >= GETDATE()

In general my stored procedure works fine, my only problem is if the targetDate equals the current date as all dates are saved as follows, ie with the time set to zeros: 一般来说我的存储过程工作正常,我唯一的问题是如果targetDate等于当前日期,因为所有日期都保存如下,即时间设置为零:

2014-02-22 00:00:00.000

How do I have to change my WHERE clause so that it only considers the date but ignores the time saved with it so that I get any records with the current date even if the time is already passed ? 我如何更改我的WHERE子句,以便它只考虑日期但忽略与它一起保存的时间,以便即使时间已经过,我也可以获得当前日期的任何记录?

Many thanks for any help with this, Tim. 蒂姆,非常感谢你提供的任何帮助。

Change to: 改成:

WHERE A.targetDate >= cast(GETDATE() as date)

Edit - because targetdate also contains time, yes, format both like this: 编辑 - 因为targetdate还包含时间,是的,格式如下:

WHERE cast(A.targetDate as date) >= cast(GETDATE() as date)

Edit - given comments re: performance, may want to try: 编辑 - 给出评论重新:表现,可能想尝试:

WHERE a.targetdate >= cast(cast(getdate() as date) as datetime)

Last edit should give you the same result and take advantage of any indexes on targetdate 上次编辑应该给你相同的结果,并利用targetdate上的任何索引

The following should give you the current date with no time: 以下内容应该为您提供当前日期,没有时间:

SELECT DATEADD(dd,0,DATEDIFF(dd,0,GETDATE()))

This should be your final line: 这应该是你的最后一行:

WHERE A.targetDate >= DATEADD(dd,0, ATEDIFF(dd,0,GETDATE()))

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

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