日期时间字段查询中的搜索日期无效

时间:2020-01-31 14:55:20

标签: sql vba ms-access

我在下面查询

 sql_query = "select * from bericht where fromtime = " & Me.von & " and b_date = #" & Me.l_date & "#"

通过调试打印以下行。

select * from bericht where fromtime = 6 and b_date = #1/30/2020#

在表中,b_datedateTime field。 (从SQL Server的Msaccess中链接的表

此表中存在1/30/2020 2:00:00 PM的数据,其中fromtime也是6。

为什么查询没有返回任何数据?

msaccess不能在datetime字段中搜索日期吗?

PS:fromtime是Intiger不是时间字段。

2 个答案:

答案 0 :(得分:2)

因为#1/30/2020# <> 1/30/2020 2:00:00 PM

在进行比较之前,将列转换为日期,而不是日期时间。

... and DateValue(b_date) = #" & Me.l_date & "#"

这将返回该日期之后满足您其他条件的所有行。

答案 1 :(得分:2)

类似地,考虑搜索日期范围内的所有日期时间,因为DateValue可能存在效率问题:

select * from bericht 
where fromtime = 6 
  and b_date >= CDate("2020-01-30") 
  and b_date < CDate("2020-01-30") + 1

并直接指向表单/报告字段。将以下内容另存为存储的查询,并根据需要在VBA中使用DoCmd.OpenQuery进行调用:

select * from bericht 
where fromtime = Forms!myForm!von 
  and b_date >= [Forms!myForm!l_date]
  and b_date < ([Forms!myForm!l_date] + 1)

如果对记录集构建使用查询,则 still 使用首选的参数化方法,而 still 使用存储的查询,并在VBA中使用QueryDefs打开它并绑定所需的{{3} }:

SQL

parameters [myint] int, [mydate] date;
select * from bericht 
where fromtime = [myint] 
  and b_date >= [mydate]
  and b_date < ([mydate] + 1)

VBA

Dim qDef As QueryDef
Dim rst As Recordset

Set qdef = CurrentDb.QueryDefs("mySavedQuery")

qdef!myint = Me.von
qdef!myDate = Me.l_date

Set rst = qdef.OpenRecordset()

...
相关问题