【问题标题】:Inline SQL statement returning only duplicate first record in recordset内联 SQL 语句仅返回记录集中重复的第一条记录
【发布时间】:2015-05-04 03:27:30
【问题描述】:

我有一个名为Employees 的表,其中包含一个名为EmployeeID 的字段。在一个单独的表中,我有一个名为 Master 的单独的员工主表,其中包含一个名为 EmployeeStatus 的字段。我正在尝试验证已从公司解雇的所有员工都未列在员工表中。

但是,我在下面使用的当前代码正在返回员工主表中第一条记录的副本。记录集对象的记录计数属性的值符合我的预期,即终止员工的总数。 rs.Fields(0) 但是只显示 Master 表中第一个匹配记录的副本。 从即时窗口中的 debug.print 中可以看出。我已经检查了以下内容:

  • 字段名称中的尾随和前导空格
  • 正确引用字符串
  • SQL 和 VBA 语法

如何修复我的代码以显示所有匹配的记录?

Public Function validEmployee(EmpID as String)

Dim dbs As DAO.database
Dim rs As DAO.recordset
Dim sqlString as String
set dbs = CurrentDb

sqlString = "SELECT [EmployeeID] FROM [MASTER] WHERE [EmployeeStatus] = 'Terminated'"

set rs = dbs.openrecordset(sqlString)
rs.moveLast
debug.print rs.recordcount
debug.print rs.fields(0)

【问题讨论】:

  • 您需要创建一个循环。在循环内,您需要移动到下一条记录。我建议您从第一条记录开始(出于某种原因,您调用了moveLast 方法
  • 您能提供[employee]、[master]表的表定义吗?我们可能会帮助您创建连接查询。

标签: sql ms-access vba


【解决方案1】:

你想遍历记录集,像这样;

        Public Function validEmployee(EmpID as String)

    Dim dbs As DAO.database
    Dim rs As DAO.recordset
    Dim sqlString as String
    set dbs = CurrentDb

    sqlString = "SELECT [EmployeeID] FROM [MASTER] WHERE [EmployeeStatus] = 'Terminated'"

    set rs = dbs.openrecordset(sqlString)
with rs
if .recordcount > 0 Then 'make sure the query returns records
    .moveLast 'move last then back to first to make sure rs knows the record count
    .movefirst
    do until .eof 'loop through until the end of the recordset
       debug.print rs.recordcount 'debug print our info
       debug.print rs.fields(0)
    loop
end if
end with
rs.close 'close off
set rs = nothing

从 aircode 输入上述内容,但它应该让您走上正轨。您当前的代码不会遍历记录,它只是调试打印字段 0 的最后记录值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-27
    • 2013-03-28
    相关资源
    最近更新 更多