查找不匹配的记录代码

时间:2017-03-04 14:46:07

标签: access

请验证以下代码,以便在MS访问中找到两个表之间的不匹配值(因为查询表达式中有运行时错误3075 Count(table1.Inv_No))'

Public Sub subCreateRowDiff()

Dim strSQL As String
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim db As DAO.Database
Dim lngCount As Long

Const TEMP_TABLE As String = "tblNoMatch"

strSQL = "SELECT table1.[Inv_No], table1.[Amt], Count(table1.Inv_No]) As Expr1 GROUP BY table1.[Inv_No], table1.[Amt];"
Set db = CurrentDb

'remove all records
db.Execute "DELETE " & TEMP_TABLE & ".* FROM " & TEMP_TABLE & ";"
'open table1
Set rs1 = db.OpenRecordset(strSQL)
strSQL = Replace(strSQL, "table1", "table2")
'open table2
Set rs2 = db.OpenRecordset(strSQL)
'check for difference
With rs1
    If Not (.BOF And .EOF) Then .MoveFirst
    While Not .EOF
        lngCount = .Fields(2).Value 'the count field
        'find matching record in table2
        rs2.FindFirst "[Inv_No] = " & .Fields(0) & " AND [Amt] = " & .Fields(1).Value
        If rs2.NoMatch Then
            'save this record as many times (lngCount)
            While lngCount <> 0
                db.Execute "Insert Into " & TEMP_TABLE & "(Inv_No, Amt) " & _
                            "Values(" & .Fields(0).Value & ", " & .Fields(1) & ");"
                lngCount = lngCount - 1
            Wend
        Else
            ' there is a match
            ' check the difference
            If .Fields(2).Value > rs2.Fields(2).Value Then
                lngCount = .Fields(2).Value - rs2.Fields(2).Value
            Else
                lngCount = rs2.Fields(2).Value - .Fields(2).Value
            End If
            While lngCount <> 0
                db.Execute "Insert Into " & TEMP_TABLE & "(Inv_No, Amt) " & _
                            "Values(" & .Fields(0).Value & ", " & .Fields(1) & ");"
                lngCount = lngCount - 1
            Wend
        End If
        .MoveNext
    Wend
End With

' now use table2 as reference
With rs2
    If Not (.BOF And .EOF) Then .MoveFirst
    While Not .EOF
        lngCount = .Fields(2).Value 'the count field
        'find matching record in table1
        rs1.FindFirst "[Inv_No] = " & .Fields(0) & " AND [Amt] = " & .Fields(1).Value
        If rs1.NoMatch Then
            'save this record as many times (lngCount)
            While lngCount <> 0
                db.Execute "Insert Into " & TEMP_TABLE & "(Inv_No, Amt) " & _
                            "Values(" & .Fields(0).Value & ", " & .Fields(1) & ");"
                lngCount = lngCount - 1
            Wend
        Else
            ' we already did this before
            ' so no need
        End If
        .MoveNext
    Wend
End With
rs1.Close: Set rs1 = Nothing
rs2.Close: Set rs2 = Nothing
Set db = Nothing

End Sub

1 个答案:

答案 0 :(得分:0)

缺少左括号[。此SQL语句中不需要括号,因为表和字段名称没有空格。