要更新現有記錄,需要比較兩個記錄,並在目標數據庫中進行更新(如果它們不相同)。
根據涉及的字段數量,這可能很複雜。
這裏的代碼中,我用過去那種目的:
Public Function UpdateTableData(ByVal strSourceTable As String, _
ByVal strTargetTable As String, ByVal strJoinField As String, _
ByRef db As DAO.Database, Optional ByVal strExcludeFieldsList As String, _
Optional strAdditionalCriteria As String) As Boolean
Dim strUpdate As String
Dim rsFields As DAO.Recordset
Dim fld As DAO.Field
Dim strFieldName As String
Dim strNZValue As String
Dim strSet As String
Dim strWhere As String
strUpdate = "UPDATE " & strTargetTable & " INNER JOIN " & strSourceTable & " ON " & strTargetTable & "." & strJoinField & " = " & strSourceTable & "." & strJoinField
' if the fields don't have the same names in both tables,
' create a query that aliases the fields to have the names of the
' target table
' if the source table is in a different database and you don't
' want to create a linked table, create a query and specify
' the external database as the source of the table
' alternatively, for strTargetTable, supply a SQL string with
' the external connect string
Set rsFields = db.OpenRecordset(strSourceTable)
For Each fld In rsFields.Fields
strFieldName = fld.Name
If strFieldName <> strJoinField Or (InStr(", " & strExcludeFieldsList & ",", strFieldName & ",") <> 0) Then
Select Case fld.Type
Case dbText, dbMemo
strNZValue = "''"
Case Else
strNZValue = "0"
End Select
strSet = " SET " & strTargetTable & "." & strFieldName & " = varZLSToNull(" & strSourceTable & "." & strFieldName & ")"
strSet = strSet & ", " & strTargetTable & ".Updated = #" & Date & "#"
strWhere = " WHERE Nz(" & strTargetTable & "." & strFieldName & ", " & strNZValue & ") <> Nz(" & strSourceTable & "." & strFieldName & ", " & strNZValue & ")"
If db.TableDefs(strTargetTable).Fields(fld.Name).Required Then
strWhere = strWhere & " AND " & strSourceTable & "." & strFieldName & " Is Not Null"
End If
If Len(strAdditionalCriteria) > 0 Then
strWhere = strWhere & " AND " & strAdditionalCriteria
End If
Debug.Print strUpdate & strSet & strWhere
Debug.Print SQLRun(strUpdate & strSet & strWhere, dbLocal) & " " & strFieldName & " updated."
End If
Next fld
rsFields.Close
Set rsFields = Nothing
UpdateTableData = True
End Function
您可以通過這個函數的兩個表名,或兩個查詢的名稱。這允許很大的靈活性。它假定字段名稱在它傳遞的兩個對象中都是相同的,並且如果它們不是相同的名稱,則可以創建一個查詢來替換字段以匹配另一個表中的字段。
這是我使用bazillion次的代碼的一個變體。基本原理是它執行一系列UPDATE查詢,逐行遍歷表並根據哪些行具有不同的值進行更新。
感謝您的回答。對不起,但我無法打開你的鏈接。 – Ekin 2010-11-02 10:18:16
對不起,我修復了這個鏈接。你現在應該可以閱讀它了。 – heferav 2010-11-02 10:28:11