访问 - 比较两个 table 并在第一个 table 中更新或插入数据

Access - compare two tables and update or insert data in first table

在我的 Access 数据库中有两个表:

表 1:

    PersNum Name    Surname
    2321    Lenora  Springer
    2320    Donya   Gugino
    3326    Leland  Wittmer
    4588    Elmer   Mcdill

表 2:

    PersNum Name    Surname
    2321    Lenora  Farney
    2320    Donya   Willimas
    3326    Leland  Wittmer
    4588    Maya    Mcdill
    7785    Yolanda Southall
    1477    Hailey  Pinner 

我需要找到一种方法来检查个人号码(字段"PersNum"),然后如果PersNum 存在,则更新Table1 中的Name 和Surname。如果 PersNum 不存在,则在 Table1 中插入新行。

预期结果:

    PersNum Name    Surname
    2321    Lenora  Farney      (updated surname)
    2320    Donya   Willimas    (updated surname)
    3326    Leland  Wittmer     (without change)
    4588    Maya    Mcdill      (without change)
    7785    Yolanda Southall    (new person)
    1477    Hailey  Pinner      (new person)

我正在寻找基于 SQL/VBA/DAO/ADO 的任何解决方案。

一个选项是 "upsert" 或组合 append/update 查询。

Smart Access 的这条旧提示是我的最爱之一:

Update and Append Records with One Query

By Alan Biggs

Did you know that you can use an update query in Access to both update and add records at the same time? This is useful if you have two versions of a table, tblOld and tblNew, and you want to integrate the changes from tblNew into tblOld.

Follow these steps:

  1. Create an update query and add the two tables. Join the two tables by dragging the key field of tblNew onto the matching field of tblOld.

  2. Double-click on the relationship and choose the join option that includes all records from tblNew and only those that match from tblOld.

  3. Select all the fields from tblOld and drag them onto the QBE grid.

  4. For each field, in the Update To cell type in tblNew.FieldName, where FieldName matches the field name of tblOld.

  5. Select Query Properties from the View menu and change Unique Records to False. (This switches off the DISTINCTROW option in the SQL view. If you leave this on you'll get only one blank record in your results, but you want one blank record for each new record to be added to tblOld.)

  6. Run the query and you'll see the changes to tblNew are now in tblOld.

    This will only add records to tblOld that have been added to tblNew. Records in tblOld that aren't present in tblNew will still remain in tblOld.