内联SQL语句仅返回记录集中重复的第一条记录

时间:2015-04-28 00:13:47

标签: sql ms-access access-vba

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

但是,我在下面使用的当前代码返回了员工主表中第一条记录的副本。记录集对象的记录计数属性的值与我期望的,终止雇员的总数相匹配。 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)

1 个答案:

答案 0 :(得分: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

从空气代码中键入上述内容,但它应该让您走在正确的轨道上。您当前的代码不会遍历记录,只是调试打印字段0的最后一个记录值。