我正在尝试比较表之间的所有字段值,并在找到不匹配的值时从两个表返回整个记录
它在第一次运行时工作正常,但是一旦进入第二个循环,我就得不到这个集合中的
If rs1.Fields(fld) <> rs2.Fields(fld) Then
这是我现在在该部分中的代码:
Private Sub Execute_Click()
DoCmd.RunSQL "Delete * FROM Issues2"
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim fld As DAO.Field
'.... set those recordsets via SQL statements
Set rs1 = CurrentDb.OpenRecordset("Full")
Set rs2 = CurrentDb.OpenRecordset("Transaction1")
For Each fld In rs1.Fields
If rs1.Fields(fld) <> rs2.Fields(fld) Then
DoCmd.RunSQL "INSERT INTO Issues2 SELECT Full.* FROM Full LEFT JOIN Transaction1 ON Full.[Member ID] = Transaction1.[Member ID] WHERE (((Transaction1.[Member ID]) Is Null));"
DoCmd.RunSQL "INSERT INTO Issues2 SELECT Transaction1.* FROM Transaction1 LEFT JOIN Full ON Transaction1.[Member ID] = Full.[Member ID] WHERE (((Full.[Member ID]) Is Null));"
End If
Next fld
有没有人知道为什么它会在第一次运行时正常工作,但在第二次循环时会出错?
答案 0 :(得分:1)
你的逻辑缺少一些关键的东西。看起来你可能想要这样的东西:
For Each fld1 In rs1.Fields
For Each fld2 In rs2.Fields
If fld1.Name = fld2.Name Then
If fld1 <> fld2 Then
DoCmd.RunSQL "INSERT INTO Issues2 ...;"
DoCmd.RunSQL "INSERT INTO Issues2 ...;"
End If
End If
Next fld2
Next fld1
以上代码更正3/5 4:45 PM CST
注意fld
已声明rs1
,但您也尝试为rs2
调用它。上面的代码提出了单独的字段变量fld1
和fld2
。
你可以自由地甩掉那些记录集。尝试:
Set rs1 = CurrentDb.OpenRecordset("Full", dbOpenSnapshot)
这样就没有rs1
试图回应变化的危险。此外,添加DoEvents
可以解决一些问题(尽管我尝试保留其用于临时调试......在您的情况下,鉴于已经引用的逻辑问题,它并不相关):
DoCmd.RunSQL "INSERT INTO Issues2 ...;"
DoEvents
DoCmd.RunSQL "INSERT INTO Issues2 ...;"
DoEvents
原始代码还有另一个严重问题。您的SQL查询不使用变量。也就是说,您重复运行相同的查询,而不是动态更改的查询。据我所知,这违背了目的。