SQL - 比较 WHERE 语句中的日期在 Access DB 中无法正常工作

标签 sql datetime ms-access

我正在尝试比较我的 SQL 语句中的两个日期。我在数据库中使用的日期格式是 DD/MM/YYYY .

当我写下面的sql时:

SELECT * FROM [MyTableName]  
WHERE #03/10/2014# >= #02/11/2014#; 

WHERE 语句的结果是True -(不好)。
根据我想要的格式 ( DD/MM/YYYY ) 它应该是 False,但是在 SQL 语句中它出现在 MM/DD/YYYY 中格式。

同样的问题在我使用Now()时出现功能:

WHERE NOW() >= #02/12/2014#; 

(今天是 2014 年 3 月 11 日)
应该是False因为11 < 12但声明仍然是正确的。 (使用 MM/DD/YYYY 格式的 SQL)。

所以我添加了一个FORMAT功能,现在看起来像这样:

WHERE FORMAT(#03/10/2014#, 'DD/MM/YYYY') >= FORMAT(#02/11/2014#, 'DD/MM/YYYY');  

这次WHERE语句的结果是Flase -(好!)
到目前为止,Format 函数看起来是一个很好的解决方案,但是当尝试重新格式化 NOW() Date 时,问题再次出现:

这个 WHERE 语句应该是 True

WHERE FORMAT(NOW(), 'DD/MM/YYYY') = FORMAT(#03/11/2014#, 'DD/MM/YYYY'); 

但它是False

虽然这个 WHERE 语句应该是 False

WHERE FORMAT(NOW(), 'DD/MM/YYYY') = FORMAT(#11/03/2014#, 'DD/MM/YYYY'); 

它是 True

(今天是 2014 年 3 月 11 日)

我们可以看到 Format 函数在 NOW() 日期上无法正常工作。
有人对此有解决方案吗?

最佳答案

# 字符分隔的日期文字通常会解释 MM/DD/YYYY 格式的 NN/NN/NNNN 格式 - 无论您的文化设置如何。

在某些情况下,例如当第一组数字大于 12 时,环境可能选择以 DD/MM/YYYY 顺序解释值只是为了处理输入,但这是您不应依赖的非标准行为。

具体来说,the VB Date Data Type 的 MSDN 文档说如下:

You must enclose a Date literal within number signs (# #). You must specify the date value in the format M/d/yyyy, for example #5/31/1993#. This requirement is independent of your locale and your computer's date and time format settings.

The reason for this restriction is that the meaning of your code should never change depending on the locale in which your application is running. Suppose you hard-code a Date literal of #3/4/1998# and intend it to mean March 4, 1998. In a locale that uses mm/dd/yyyy, 3/4/1998 compiles as you intend. But suppose you deploy your application in many countries. In a locale that uses dd/mm/yyyy, your hard-coded literal would compile to April 3, 1998. In a locale that uses yyyy/mm/dd, the literal would be invalid (April 1998, 0003) and cause a compiler error.

对于 VB、VBA 和 MS Access 都是如此。

解决此问题的一种方法是使用日期文字。相反,请考虑使用 DateValue函数在查询之前将字符串解析为日期对象。

关于SQL - 比较 WHERE 语句中的日期在 Access DB 中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26719241/

相关文章:

c++ - 通过 odb-orm 连接到 ms-access

mysql - SQL 子字符串问题(其中子字符串(...)=(选择...))

sql - 如何在没有序列的情况下自动增加 SQL Server 2016 合并插入中的主键?

mysql - SQL查询以计算所有具有按主键分割的重复值的行

php - Yii:如何在 View 中格式化日期时间并按年份搜索

MySQL 查询 - 最近的月份/年份

vb.net - 导出 Access 图像格式的图表?

sql - 以随机顺序返回行

mysql - 要删除的 SQL 查询

ms-access - 微软 Access : How to filter report on non-report field?