Public Function SynchTableFromMaster( _
MasterDB As String, _
TableName As String, _
PKeyName As String) As Boolean
Const cTempTable = "tmpSynchTable"
Dim db As DAO.Database
Dim tbl As DAO.TableDef
Dim fld As DAO.Field
Dim sSQL As String
Dim sSourceFields As String
Dim sDestFields As String
Dim iSynched As Integer
Dim iAdded As Integer
On Error GoTo ProcErr
Set db = CurrentDb
' first link the master table
On Error Resume Next
' delete the temp linked table if it exists
db.TableDefs.Delete cTempTable
On Error GoTo ProcErr
Set tbl = db.CreateTableDef(cTempTable)
tbl.SourceTableName = TableName
tbl.Connect = ";DATABASE=" & MasterDB
db.TableDefs.Append tbl
' construct a SQL string for the update query
sSQL = "UPDATE " & TableName & " as T inner join " & cTempTable _
& " as S on T.[" & PKeyName & "]=S.[" & PKeyName & "] SET "
For Each fld In tbl.Fields
If fld.Name <> PKeyName Then
sSQL = sSQL & "T.[" & fld.Name & "]=S.[" & fld.Name & "], "
End If
Next fld
' remove last ", " and add ";"
sSQL = Left(sSQL, Len(sSQL) - 2) & ";"
db.Execute sSQL, dbFailOnError
iSynched = db.RecordsAffected
' construct a SQL string for the append query
sSQL = "INSERT INTO " & TableName & " SELECT * FROM " & cTempTable _
& " where [" & PKeyName & "] not in (select [" & PKeyName _
& "] from " & TableName & ");"
db.Execute sSQL, dbFailOnError
iAdded = db.RecordsAffected
MsgBox iSynched & " existing records synchronized" _
& vbCrLf & iAdded & " new records added"
SynchTableFromMaster = True
ProcEnd:
On Error Resume Next
db.TableDefs.Delete cTempTable
Exit Function
ProcErr:
MsgBox "Error synching table " & TableName & vbCrLf _
& vbCrLf & Err.Description
Resume ProcEnd
End Function
|