【问题标题】:date range not working in vb with ms access database日期范围在带有 ms 访问数据库的 vb 中不起作用
【发布时间】:2011-05-25 14:25:59
【问题描述】:

我需要更新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") & " "

【问题讨论】:

  • 能否提供表结构

标签: sql ms-access vb6


【解决方案1】:

正如@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 的日期,本月应该发生什么?您的 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's page about sandbox mode functions)。

编辑:感谢@Brian Camire 的建议。

Debug.Print "WHERE pdate < " & _
    "DateSerial(Year(Date), Month(Date), 1)" & _
    " OR pdate >= " & _
    "DateSerial(Year(Date), Month(Date), 21)"

【讨论】:

  • 不依赖日期文字或分隔符的这种方法的变体可能是:WHERE pdate &lt; DateSerial(Year(Date), Month(Date), 1) OR pdate &gt;= DateSerial(Year(Date), Month(Date), 21)
  • @HansUp,你怎么知道引擎会在我的例子中多次执行这些函数。一篇旧的 MSDN 文章 link 声称,“如果表达式不引用字段,则每个查询仅调用一次函数”。
  • @Brian Camire 我不知道,懒得用 SHOWPLAN 找出来。我删除了该评论并添加了您的建议。谢谢。
  • +1 表示@Brian Camire 的建议,即在 SQL 代码中使用时间函数,而不是在 VBA 中构造日期文字值。
  • @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

【讨论】:

  • 不客气。请记住,如果有帮助,您可以投票和/或接受答案... ;-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 1970-01-01
  • 2017-02-24
相关资源
最近更新 更多