SQL Server:将日期时间与 GETDATE() 进行比较
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21958829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Server: compare datetime day with GETDATE()
提问by user2571510
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. My corresponding WHERE clause is the following:
我有一个存储过程,它应该获取日期等于当前日期或将来的所有记录。日期保存在 targetDate 列中并格式化为 datetime。我对应的 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, i.e. 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.
非常感谢您对此的任何帮助,蒂姆。
回答by Brian DeMilia
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 上的任何索引
回答by Preli
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()))