2012-04-04 131 views
0

如何比較兩個MS ACCESS 2007數據庫。兩個數據庫都包含具有相同表格的相同表格ad structure.i需要比較兩個數據庫之間的記錄值以檢測記錄中的任何差異值。如何比較兩個訪問數據庫以比較數據庫記錄

      ACCESS 2007 Database1         

      serial no.  | NAME   | ADDRESS     
       1    smith   street 1         
       2    john   street 4         
       3    alix   street 8     


          ACCESS 2007 Database2 

       serial no.| NAME  | ADDRESS 
       1   smith  street 1    
       2   jhn  stret 4    
       3   alix  street 8 

我需要一個可以檢測記錄差異的ms訪問的VBA代碼,就像序列號爲2的記錄一樣。

回答

0

你應該做的第一件事是將其中一個錶鏈接到另一個數據庫,例如,將Database 2錶鏈接到數據庫1(這可以一起查詢這兩個表),然後你可以使用這個簡單的例子連接來確定如果所有字段串在一起匹配基於序列號:

SELECT T1.*, T2.* 
FROM Table1 As T1, Table2 As T2 
WHERE T2.[serial no.] = T1.[serial no.] 
AND T2.[NAME] & T2.[ADDRESS] <> T1.[NAME] & T1.[ADDRESS] 

如果您願意,您也可以指定具有各自條件的列。 注意:這是假設您只查找序列號不匹配的區別,如果您還需要識別可能出現在一個表中但不是另一個表中的記錄,則需要使用「不匹配」查詢,查詢設計人員可以幫助您解決這個問題,或者回復並且我可以更新我的答案。

0
Option Compare Database 

Private Sub Command4_Click() 

Dim tablename1, tablename2 As String 
tablename1 = Text0.Value 
tablename2 = Text2.Value 

'On Error GoTo Err_cmdValidateGeneralInfo_Click 
Dim F As DAO.Field 
Dim rs As DAO.Recordset 
Dim rs1 As DAO.Recordset 
Set curDB = CurrentDb() 
'If Me.DateModified = Date Then 
    'Adds new employees to the TT_GeneralInfo table in the FTEI_PhoneBook.mdb - which is used thru out the AP databases. 
' DoCmd.OpenQuery "qryEmpData_TT_General" 

strsql = "Select * from " & tablename1 

Set rs = curDB.OpenRecordset(strsql) 

strsql1 = "Select * from " & tablename2 

    DoCmd.CopyObject , "Unmatched_records", acTable, tablename1 
    curDB.Execute "DELETE FROM Unmatched_records" 

Set rs1 = curDB.OpenRecordset(strsql1) 
    Do Until rs.EOF 
     For Each F In rs.Fields 
     If rs.Fields(F.Name) <> rs1.Fields(F.Name) Then 
      'rs.Edit 
      strsql = "Select * into test from " & tablename1 & " where " & F.Name & " = """ & rs.Fields(F.Name) & """" 
      DoCmd.RunSQL strsql 

      If DCount(F.Name, "test") <> 0 Then 
      GoTo append_unmatch 

      'appending unmacthed records 
append_unmatch: 

      strsql2 = "insert into Unmatched_records Select * from test" 
      DoCmd.RunSQL strsql2 

      'if record doesnt match move to next one 
      GoTo Nextrecord 
      End If 
     ' rs.Fields(F.Name) = rs1.Fields(F.Name) 
     ' rs.Update 
     End If 
     Next F 

Nextrecord: 
rs.MoveNext 
rs1.MoveNext 
    Loop 

    'To check whether tables matched or not 
    Dim rs2 As DAO.Recordset 
    strsql3 = "select * from Unmatched_records" 
    Set rs2 = curDB.OpenRecordset(strsql3) 
    For Each F In rs2.Fields 
    If DCount(F.Name, "Unmatched_records") <> 0 Then 
    MsgBox ("The two tables didnt match. Check table test for unmatching reocrds.") 
    Else 
    MsgBox ("Tables match!") 
    End If 
Exit Sub 
    Next F 
    rs2.Close 


    End Sub 
+2

儘管代碼片段可以回答這個問題,但仍然非常適合添加一些附加信息,如解釋等。 – j0k 2012-12-28 09:14:20