VB中使用MS Access数据库时日期范围不起作用

3

我需要更新那些

pdate(一个日期字段)不在当前月份和年份的1日到20日之间的行。

我正在使用下面的代码,但它会出现错误,显示“需要更多参数,期望1个”。我正在使用MS Access 2007作为数据库。

cn.Execute "update water set prel = (prel + (mmt * (tx / 100))) where pdate not between 1-" & Format$(Now, "MMM") & "-" & Format$(Now, "YYYY") & "  and 20-" & Format$(Now, "MMM") & "-" & Format$(Now, "YYYY") & " "

你能提供表结构吗? - Vineet1982
2个回答

6
你的紧急问题是缺少 # 日期分隔符,就像 @MicSim 给你展示的那样。但是我建议你考虑一种不同的 WHERE 子句方法。
在添加 # 分隔符后,你的 WHERE 子句类似于这个(使用今天的日期)。
Debug.Print "WHERE pdate not between #1-" & _
    Format$(Now, "MMM") & "-" & Format$(Now, "YYYY") & _
    "# and #20-" & Format$(Now, "MMM") & "-" & _
    Format$(Now, "YYYY") & "#"
WHERE pdate not between #1-May-2011# and #20-May-2011#

一个重要问题是你的所有日期值是否都包含午夜作为时间组成部分。(日期/时间值始终包含时间组成部分。)这个问题之所以重要是因为对于2011年5月20日10:18:15 AM的日期,应该发生什么?你的WHERE子句将导致更新。但是那个日期仍然是5月20日...这是你想要的吗?
我认为使用修订后的WHERE子句风险更小。
Debug.Print "WHERE pdate < " & _
    Format(DateSerial(Year(Date), Month(Date), 1), "\#yyyy-mm-dd#\") & _
    " OR pdate >= " & _
    Format(DateSerial(Year(Date), Month(Date), 21), "\#yyyy-mm-dd#\")
WHERE pdate < #2011-05-01# OR pdate >= #2011-05-21#

你的问题被标记为vb6。DateSerial()、Year()、Month()、Date()和Format()函数应该都可以从数据库引擎的沙盒模式中使用。(参见Microsoft有关沙盒模式函数的页面)。 编辑: 感谢@Brian Camire提出的建议。
Debug.Print "WHERE pdate < " & _
    "DateSerial(Year(Date), Month(Date), 1)" & _
    " OR pdate >= " & _
    "DateSerial(Year(Date), Month(Date), 21)"

1
一种不依赖于日期字面值或分隔符的这种方法的变化形式可能是:WHERE pdate < DateSerial(Year(Date), Month(Date), 1) OR pdate >= DateSerial(Year(Date), Month(Date), 21) - Brian Camire
@HansUp,你怎么知道引擎会在我的示例中执行函数多次。一篇旧的MSDN文章链接声称,如果表达式不引用字段,则每个查询只会调用一次函数。 - Brian Camire
@Brian Camire 我不知道,也懒得使用SHOWPLAN去找。我删掉了那个评论并加入了你的建议。谢谢。 - HansUp
+1 对 @Brian Camire 的建议,即在 SQL 代码中使用时间函数而不是在 VBA 中构造日期文字值。 - onedaywhen
@HansUp:没有,区别在于你的回答 :) 我已经编辑了你的回答并删除了我的评论。 - onedaywhen
@onedaywhen 谢谢您修复了我的回答中的引号。在您和Brian的帮助下,也许我能得到更多分数。 :-) - HansUp

2
你需要使用哈希符号或单引号来限定日期,具体取决于你使用的数据库接口。如果是使用 ANSI 92 或 ADO/OLEDB 接口,请使用哈希符号 (#):
cn.Execute "update water set prel = (prel + (mmt * (tx / 100))) 
where pdate not between 
    #1-" & Format$(Now, "MMM") & "-" & Format$(Now, "YYYY") & "#  
        and #20-" & Format$(Now, "MMM") & "-" & Format$(Now, "YYYY") & "# "

虽然在这种情况下,我建议使用一般格式yyyy-mm-dd hh:mm:ssyyyy-mm-dd


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接