Upserting in MS-access

后端 未结 5 1470
天涯浪人
天涯浪人 2020-11-22 15:29

I need to write an SQL query for MS-Access 2000 so that a row is updated if it exists, but inserted if it does not. (I believe this is called an \"upsert\")

i.e.

相关标签:
5条回答
  • 2020-11-22 16:06

    An "upsert" is possible, if the tables have a unique key.

    This old tip from Smart Access is one of my favourites:

    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:

    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.

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

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

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

    4. 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.)

    5. 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.

    0 讨论(0)
  • 2020-11-22 16:06

    Assuming a unique index on Column1, you can use a DCount expression to determine whether you have zero or one row with Column1 = 'SomeValue'. Then INSERT or UPDATE based on that count.

    If DCount("*", "Table1", "Column1 = 'SomeValue'") = 0 Then
        Debug.Print "do INSERT"
    Else
        Debug.Print "do UPDATE"
    End If
    

    I prefer this approach to first attempting an INSERT, trapping the 3022 key violation error, and doing an UPDATE in response to the error. However I can't claim huge benefits from my approach. If your table includes an autonumber field, avoiding a failed INSERT would stop you from expending the next autonumber value needlessly. I can also avoid building an INSERT string when it's not needed. The Access Cookbook told me string concatenation is a moderately expensive operation in VBA, so I look for opportunities to avoid building strings unless they're actually needed. This approach will also avoid creating a lock for an unneeded INSERT.

    However, none of those reasons may be very compelling for you. And in all honesty I think my preference in this case may be about what "feels right" to me. I agree with this comment by @David-W-Fenton to a previous Stack Overflow question: "It's better to write your SQL so you don't attempt to append values that already exist -- i.e., prevent the error from happening in the first place rather than depending on the database engine to save you from yourself."

    0 讨论(0)
  • 2020-11-22 16:10

    I usually run the insert statement first and then I check to see if error 3022 occurred, which indicates the row already exists. So something like this:

    On Error Resume Next
    CurrentDb.Execute "INSERT INTO Table1 (Fields) VALUES (Data)", dbFailOnError
    If Err.Number = 3022 Then
        Err.Clear        
        CurrentDb.Execute "UPDATE Table1 SET (Fields = Values) WHERE Column1 = 'SomeValue'", dbFailOnError
    ElseIf Err.Number <> 0 Then
        'Handle the error here
        Err.Clear
    End If
    

    Edit1:
    I want to mention that what I've posted here is a very common solution but you should be aware that planning on errors and using them as part of the normal flow of your program is generally considered a bad idea, especially if there are other ways of achieving the same results. Thanks to RolandTumble for pointing this out.

    0 讨论(0)
  • 2020-11-22 16:11

    You can simulate an upsert in an Access by using an UPDATE query with a LEFT JOIN.

    update b
    left join a on b.id=a.id
    set a.f1=b.f1
    , a.f2=b.f2
    , a.f3=b.f3
    

    see: https://www.experts-exchange.com/questions/28713136/Can-I-use-the-SQL-MERGE-statement-in-a-query-in-Access-2010.html

    0 讨论(0)
  • 2020-11-22 16:12

    You don't need to catch the error. Instead, just run the INSERT statement and then check

    CurrentDb.RecordsAffected
    

    It will either be 1 or 0, depending.

    Note: It's not good practice to execute against CurrentDB. Better to capture the database to a local variable:

    Dim db As DAO.Database
    Set db = CurrentDb
    db.Execute(INSERT...)
    If db.RecordsAffected = 0 Then
      db.Execute(UPDATE...)
    End If
    
    0 讨论(0)
提交回复
热议问题