I am using Access 2007, can someone please help me with how to
copy data to another table in the same DB when one table gets
updated?
There are valid reasons for needing to do this, such as when you
have to synchronize data stored in two different formats.
I've done this many times, and the key is DAO code that does three
things (but it assumes a PK in the table):
1. check for new records on each side, append to the other side.
2. check for deletes on each side, delete from the other (this
really has to be done via a DELETE flag, since otherwise, there's no
way you can tell the difference between a delete in database A and
an add in database B).
3. write on-the-fly SQL to update each column of the existing
records where they don't exist.
The first two are quite easy. The latter is more complicated. I use
a DAO recordset with the updatable fields, and then walk the .Fields
collection of the recordset to construct the SQL string that updates
the non-equal fields. You'd have something like this:
For each fld in rs.Fields
strField = fld.Name
strWhere = "Nz(" & strTable1 & "." & strField ",'')<>Nz(" _
& strTable2 & "." & strField ",'')"
strSQL = "UPDATE " & strTable2 & "." & strField _
& " SET " & strField & "=" & strTable1 & "." & strField
DBEngine(0)(0).Execute strSQL, dbFailOnError
Next fld
That's the basics. Obviously, you'd declare your variables and all
that, and you'd probably need a CASE SELECT in order to have Nz()
statements relevant to the specific data types of the fields, but
the idea here is that you issue one SQL UPDATE statement for each
column.
I've implemented this many, many times, in fact.