SQL 使用 MSSQL GetDate() 时如何获取日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4809956/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 09:03:18  来源:igfitidea点击:

How do I get just the date when using MSSQL GetDate()?

sqlsql-servertsqldatedatetime

提问by sooprise

DELETE from Table WHERE Date > GETDATE();

GETDATE() includes time. Instead of getting

GETDATE() 包括时间。而不是得到

2011-01-26 14:58:21.637

How can I get:

我怎样才能得到:

2011-01-26 00:00:00.000

回答by gbn

Slight bias to SQL Server

对 SQL Server 的轻微偏见

Summary

概括

DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)

SQL Server 2008 has datetype though. So just use

date虽然SQL Server 2008 有类型。所以只需使用

CAST(GETDATE() AS DATE)

Edit: To add one day, compare to the day before "zero"

编辑:要添加一天,请与“零”前一天进行比较

DATEADD(day, DATEDIFF(day, -1, GETDATE()), 0)

From cyberkiwi:

来自网络猕猴桃:

An alternative that does not involve 2 functions is (the +1 can be in or ourside the brackets).

不涉及 2 个函数的替代方法是(+1 可以在括号内或括号内)。

DATEDIFF(DAY, 0, GETDATE() +1)

DateDiffreturns a number but for all purposes this will work as a date wherever you intend to use this expression, except converting it to VARCHAR directly - in which case you would have used the CONVERT approach directly on GETDATE(), e.g.

DateDiff返回一个数字,但出于所有目的,这将在您打算使用此表达式的任何地方用作日期,除了直接将其转换为 VARCHAR - 在这种情况下,您将直接在 GETDATE() 上使用 CONVERT 方法,例如

convert(varchar, GETDATE() +1, 102)

回答by RichardTheKiwi

For SQL Server 2008, the best and index friendly way is

对于 SQL Server 2008,最好的和索引友好的方式是

DELETE from Table WHERE Date > CAST(GETDATE() as DATE);

For prior SQL Server versions, date maths will work faster than a convert to varchar. Even converting to varchar can give you the wrong result, because of regional settings.

对于以前的 SQL Server 版本,日期数学运算将比转换为 varchar 更快。由于区域设置,即使转换为 varchar 也会给您错误的结果。

DELETE from Table WHERE Date > DATEDIFF(d, 0, GETDATE());

Note: it is unnecessary to wrap the DATEDIFFwith another DATEADD

注意:没有必要DATEDIFF用另一个包裹DATEADD

回答by FolksLord

It's database specific. You haven't specified what database engine you are using.

这是特定于数据库的。您尚未指定正在使用的数据库引擎。

e.g. in PostgreSQL you do cast(myvalue as date).

例如,在 PostgreSQL 中你做 cast(myvalue as date)。

回答by JohnOpincar

SELECT CONVERT(DATETIME, CONVERT(varchar(10), GETDATE(), 101))

回答by Shafeeq Koorimannil

You can use

您可以使用

DELETE from Table WHERE Date > CONVERT(VARCHAR, GETDATE(), 101);

回答by Saggio

CONVERT(varchar,GETDATE(),102)