【发布时间】:2017-03-06 13:29:41
【问题描述】:
我正在尝试比较 access VBA 中的两个记录集,以检查两个表中的值是否相同或是否不同。两个记录集具有相同的结构(字段标题)和记录 ID,我正在尝试检查记录的字段值是否与第二个记录集中的相应字段值匹配。记录 ID 字段名称为 MATNR。
我想我已经设法遍历了第一个记录集的记录和字段,但我不确定如何遍历这些记录并将这些记录与第二个记录进行比较。另外,除了If rs1.Fields(fld.Name) = rs2.Fields(fld.Name)之外,还有更聪明的方法来比较记录集吗?
任何帮助将不胜感激。
Public Sub VerifyRecords()
Dim rs As DAO.Recordset
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim rs3 As DAO.Recordset
Dim fld As DAO.Field
Dim sSQL As String
Dim sSQL1 As String
Dim sSQL2 As String
Set rs = CurrentDb.OpenRecordset("R2_Tables_to_Compare1") 'This table lists the upload tables to query and their corresponding target tables
Set rs3 = CurrentDb.OpenRecordset("RecordValueComparisonResults") 'Write the results of the record vlaue comparison to here
'**************************************************************************************
'This SQL statement selects all records from the upload table
sSQL = "SELECT * "
sSQL = sSQL & " FROM " & rs(0)
Set rs1 = CurrentDb.OpenRecordset(sSQL)
'**************************************************************************************
'This SQL statement selects only those records that are applicable in the target table
sSQL1 = "SELECT " & rs(1) & ".* FROM " & rs(1) & " INNER JOIN " & rs(0) & " ON " & rs(1) & ".MATNR = " & rs(0) & ".MATNR"
Set rs2 = CurrentDb.OpenRecordset(sSQL1)
'**************************************************************************************
Do While Not rs1.EOF
For Each fld In rs1.Fields
If rs1.Fields(fld.Name) = rs2.Fields(fld.Name) Then
Debug.Print rs1.Fields("MATNR"), rs2.Fields("MATNR"), fld.Name, rs1.Fields(fld.Name), rs2.Fields(fld.Name)
End If
Next fld
rs1.MoveNext
Loop
rs.Close
rs1.Close
rs2.Close
rs3.Close
Set rs = Nothing
Set rs1 = Nothing
Set rs2 = Nothing
Set rs3 = Nothing
End Sub
【问题讨论】:
-
如果您正在处理 RDBMS 中的记录并开始考虑循环,那么您做错了。可以肯定的是,它所做的任何事情都可以表示为一个普通的 SQL 查询。