Solutions for INSERT OR UPDATE on SQL Server

后端 未结 22 2039
别跟我提以往
别跟我提以往 2020-11-21 22:23

Assume a table structure of MyTable(KEY, datafield1, datafield2...).

Often I want to either update an existing record, or insert a new record if it does

22条回答
  •  面向向阳花
    2020-11-21 22:55

    Does the race conditions really matter if you first try an update followed by an insert? Lets say you have two threads that want to set a value for key key:

    Thread 1: value = 1
    Thread 2: value = 2

    Example race condition scenario

    1. key is not defined
    2. Thread 1 fails with update
    3. Thread 2 fails with update
    4. Exactly one of thread 1 or thread 2 succeeds with insert. E.g. thread 1
    5. The other thread fails with insert (with error duplicate key) - thread 2.

      • Result: The "first" of the two treads to insert, decides value.
      • Wanted result: The last of the 2 threads to write data (update or insert) should decide value

    But; in a multithreaded environment, the OS scheduler decides on the order of the thread execution - in the above scenario, where we have this race condition, it was the OS that decided on the sequence of execution. Ie: It is wrong to say that "thread 1" or "thread 2" was "first" from a system viewpoint.

    When the time of execution is so close for thread 1 and thread 2, the outcome of the race condition doesn't matter. The only requirement should be that one of the threads should define the resulting value.

    For the implementation: If update followed by insert results in error "duplicate key", this should be treated as success.

    Also, one should of course never assume that value in the database is the same as the value you wrote last.

提交回复
热议问题