如何在Access查询中获取日期

发布于 2024-11-02 18:28:51 字数 310 浏览 1 评论 0原文

在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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

箹锭⒈辈孓 2024-11-09 18:28:51

您的文字日期值 #20/4/2010# 实际上是一个日期/时间值,表示 4 月 20 日午夜。请在立即窗口中查看此示例,该窗口使用 Format() 函数显示完整的日期/时间值由该文字表示。

? Format(#20/4/2010#, "d/m/yyyy hh:nn:ss AMPM")
20/4/2010 12:00:00 AM

因此,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 值转换为同一日期的午夜。此查询应返回您所期望的结果:

SELECT * FROM tblTest WHERE DateValue(CreateDate) <= #20/4/2010#

另一种方法是使用一天后的午夜作为您的截止值。

SELECT * FROM tblTest WHERE CreateDate < #21/4/2010#

第二个查询的执行速度明显更快,因为它不需要将 DateValue() 函数应用于 tblTest 中的每个 CreateDate 值。如果 CreateDate 已建立索引,第二个查询将会更快。第一个查询将无法利用 CreateDate 上的索引。

另外,我更喜欢对文字值使用明确的日期格式,因此将这样编写查询:

SELECT * FROM tblTest WHERE CreateDate < #2010/4/21#

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.

? Format(#20/4/2010#, "d/m/yyyy hh:nn:ss AMPM")
20/4/2010 12:00:00 AM

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:

SELECT * FROM tblTest WHERE DateValue(CreateDate) <= #20/4/2010#

Another approach is to use midnight one day later as your cut-off value.

SELECT * FROM tblTest WHERE CreateDate < #21/4/2010#

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:

SELECT * FROM tblTest WHERE CreateDate < #2010/4/21#
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文