如何在Access查询中获取日期
在Access 2000中,我们可以使用哪个函数来仅返回日期值?
CreateDate 20/4/2010 2:32:00 AM 20/4/2010 2:32:00 PM 19/4/2010 10:14:00 AM 17/5/2010 9:34:00 PM
如果我查询:
SELECT * FROM tblTest WHERE CreateDate <= #20/4/2010#
我只看到 2010 年 4 月 19 日的记录。
实际上,结果应该显示前3条记录,不是吗?
In Access 2000, which function could we use to get back the date value only?
CreateDate 20/4/2010 2:32:00 AM 20/4/2010 2:32:00 PM 19/4/2010 10:14:00 AM 17/5/2010 9:34:00 PM
If I query with:
SELECT * FROM tblTest WHERE CreateDate <= #20/4/2010#
I just see the 19/4/2010 record only.
Actually, the result should display first 3 records, shouldn't it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的文字日期值 #20/4/2010# 实际上是一个日期/时间值,表示 4 月 20 日午夜。请在立即窗口中查看此示例,该窗口使用 Format() 函数显示完整的日期/时间值由该文字表示。
因此,20/4/2010 2:32:00 AM 和 20/4/2010 2:32:00 PM 都被 WHERE 条件排除,因为它们大于 20/4/2010 12:00:00 AM。
如果您在 Access 会话中运行查询,则可以使用 DateValue() 函数将 CreateDate 值转换为同一日期的午夜。此查询应返回您所期望的结果:
另一种方法是使用一天后的午夜作为您的截止值。
第二个查询的执行速度明显更快,因为它不需要将 DateValue() 函数应用于 tblTest 中的每个 CreateDate 值。如果 CreateDate 已建立索引,第二个查询将会更快。第一个查询将无法利用 CreateDate 上的索引。
另外,我更喜欢对文字值使用明确的日期格式,因此将这样编写查询:
Your literal date value, #20/4/2010#, is actually a Date/Time value which represents midnight on Apr. 20. See this example from the Immediate Window which uses the Format() function to display the full Date/Time value represented by that literal.
So both 20/4/2010 2:32:00 AM and 20/4/2010 2:32:00 PM are excluded by your WHERE condition because they are greater than 20/4/2010 12:00:00 AM.
If you're running the query within an Access session, you can use the DateValue() function to convert your CreateDate values to midnight of the same date. This query should return what you expected:
Another approach is to use midnight one day later as your cut-off value.
The second query could execute significantly faster because it wouldn't require applying the DateValue() function to every CreateDate value in tblTest. And if CreateDate is indexed, the second query would be faster still. The first query would not be able to take advantage of an index on CreateDate.
Also I prefer to use an unambiguous date format for literal values, so would write the query like this: