Append everything if a new customer exists
I have a function that appends only those customers that do not exist.It works,but i want to improve it,since i have to enumerate
all the fields,which sometimes are numerous.I want to have a common function to simplify the matter.
For a similar case, for updating i have received from the Moderator Hans in the present forum, an excellent function called Public Function UpdateTable(SourceTable As String, TargetTable As String, LinkField As String). I use this functioin with success but i cannot redesignit for the append function.Can somebody help me?
The append function i use is :
Dim StrAppendCustomer As String
StrAppendCustomer = “INSERT INTO customers (CustomerID,CompanyName) ” & _
“SELECT o1.customerid, o1.companyname ” & _
” FROM customers1 As o1 WHERE NOT EXISTS (SELECT * FROM Customers WHERE CustomerID=o1.CustomerID) ”
CurrentDb.Execute StrAppendCustomer
End Sub
In the above function i have mentioned only 2 fields,CustomerID and CompanyName, but actually the tablke contains a lot of fields
and that is why i want to avoid their enumeration.
Just for information the function received from Hans for updating
is the following:
Public Function UpdateTable(SourceTable As String, TargetTable As
String, LinkField As String)
Dim strSQL As String
Dim dbs As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
On Error GoTo ErrHandler
Set dbs = CurrentDb
Set tdf = dbs.TableDefs(SourceTable)
strSQL = “UPDATE [” & TargetTable & “] INNER JOIN [” & SourceTable
& “] ” & _
“ON [” & TargetTable & “].[” & LinkField & ” ]=[” & SourceTable
& “].[” & LinkField & “] ” & _
“SET ”
For Each fld In tdf.Fields
If Not (fld.Name = LinkField) Then
strSQL = strSQL & “[” & TargetTable & “].[” & fld.Name &
“]=” & _
“[” & SourceTable & “].[” & fld.Name & “], ”
End If
Next fld
‘ Get rid of last “, ”
strSQL = Left(strSQL, Len(strSQL) – 2)
‘ Execute update query
dbs.Execute strSQL, dbFailOnError
ExitHandler:
‘ Clean up
Set fld = Nothing
Set tdf = Nothing
Set dbs = Nothing
Exit Sub
ErrHandler:
‘ Report error, then go to cleaning up section
MsgBox Err.Description, vbExclamation
Resume ExitHandler
End Sub
Call this function in the following manner:
UpdateTable SourceTable:=”CallClients1″, TargetTable:=”CallClients”,
LinkField:=”CallID”
or simply
UpdateTable “CallClients1”, “CallClients”, “CallID”
Regards,
Hans