SQL Server:如何从日期时间列中选择具有特定日期的记录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24192166/
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: how to select records with specific date from datetime column
提问by Mike
I am pretty new to SQL and hope someone here can help me with this:
我对 SQL 很陌生,希望这里有人可以帮助我:
I have a table with one column dateX
formatted as datetime and containing standard dates.
How can I select all records from this table where this dateX equals a certain date, e.g. May 9, 2014 ?
我有一个表格,其中一列dateX
格式为日期时间并包含标准日期。如何从此表中选择此 dateX 等于某个日期(例如 2014 年 5 月 9 日)的所有记录?
I tried the following but this returns nothing even if I have several records with this date.
我尝试了以下操作,但即使我在此日期有几条记录,也不会返回任何内容。
SELECT *
FROM dbo.LogRequests
WHERE (CONVERT(VARCHAR(10), dateX, 101) = '09/05/14')
Edit: In the database the above example looks as follows, using SQL 2012: 2014-05-09 00:00:00.000
编辑:在数据库中,上面的示例如下所示,使用 SQL 2012: 2014-05-09 00:00:00.000
Many thanks for any help with this, Mike.
非常感谢您对此的任何帮助,迈克。
回答by Gordon Linoff
The easiest way is to convert to a date:
最简单的方法是转换为日期:
SELECT *
FROM dbo.LogRequests
WHERE cast(dateX as date) = '2014-05-09';
Often, such expressions preclude the use of an index. However, according to various sources on the web, the above is sargable (meaning it will use an index), such as thisand this.
通常,此类表达式会排除索引的使用。但是,根据网络上的各种消息来源,上述内容是 sargable(意味着它将使用索引),例如this和this。
I would be inclined to use the following, just out of habit:
我倾向于使用以下内容,只是出于习惯:
SELECT *
FROM dbo.LogRequests
WHERE dateX >= '2014-05-09' and dateX < '2014-05-10';
回答by Ravi Shrimali
For Perfect DateTime
Match in SQL Server
用于DateTime
SQL Server 中的完美匹配
SELECT ID FROM [Table Name] WHERE (DateLog between '2017-02-16 **00:00:00.000**' and '2017-12-16 **23:59:00.999**') ORDER BY DateLog DESC
回答by Binitta Mary
SELECT *
FROM LogRequests
WHERE cast(dateX as date) between '2014-05-09' and '2014-05-10';
This will select all the data between the 2 dates
这将选择两个日期之间的所有数据