Upserting in MS-access

后端 未结 5 1583
天涯浪人
天涯浪人 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: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.

提交回复
热议问题