用于在两个日期和时间之间选择数据的 SQL 查询
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34142967/
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 query to select data between two dates and times
提问by Aaron Feng
There is a [time]
field in my table, which is a DateTime variable, the format just like 2014-04-08 23:55:00.000
. I want to select all the records between two specific dates and times.
[time]
我的表中有一个字段,它是一个 DateTime 变量,格式就像2014-04-08 23:55:00.000
. 我想选择两个特定日期和时间之间的所有记录。
such like this:
像这样:
SELECT * FROM [table]
WHERE time >=2014-04-08 23:53:00.000 AND time <= 2014-04-08 23:58:00.000
I write a SQL
我写了一个SQL
SELECT * FROM [table]
WHERE time BETWEEN #4/19/2014 12:00:00 AM# and #4/19/2014 12:30:00 AM#
But this doesn't work. Error code is:
但这不起作用。错误代码是:
Incorrect syntax near '12'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
'12' 附近的语法不正确。
说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其在代码中的来源的更多信息。
回答by Joel Coehoorn
You need single quotes around the values:
您需要在值周围使用单引号:
SELECT * FROM [table]
WHERE [time] >='2014-04-08 23:53:00.000' AND [time] <= '2014-04-08 23:58:00.000'
While I'm here, you are mistaken about how the data is formatted. The yyy-MM-dd HH:mm:ss.fff
format is just a convenience shown for you by visual studio, management studio, or your query tool. Datetime columns are actually stored in a binary format that is not human readable.
当我在这里时,您误解了数据的格式。该yyy-MM-dd HH:mm:ss.fff
格式只是由Visual Studio,管理工作室,或者你的查询工具,您可以显示一个方便。日期时间列实际上以人类无法阅读的二进制格式存储。
回答by DeanOC
You need to put the datetime values in quotes. I personally also drop the milliseconds component as this has caused me problems in the past. You would also be safest to put brackets around your time
column name so that it doesn't get treated as a restricted term.
您需要将日期时间值放在引号中。我个人也放弃了毫秒组件,因为这在过去给我带来了问题。最安全的做法是在time
列名周围加上括号,这样它就不会被视为受限制的术语。
SELECT * FROM [table]
WHERE [time] >='2014-04-08 23:53:00' AND [time] <= '2014-04-08 23:58:00'
Since you are specifying >=
and <=
, you can also simplify your statement by using the BETWEEN
operator.
由于您指定了>=
and <=
,您还可以使用BETWEEN
运算符来简化您的语句。
SELECT * FROM [table]
WHERE [time] BETWEEN '2014-04-08 23:53:00' AND '2014-04-08 23:58:00'