Solutions for INSERT OR UPDATE on SQL Server

后端 未结 22 2040
别跟我提以往
别跟我提以往 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 23:00

    Assuming that you want to insert/update single row, most optimal approach is to use SQL Server's REPEATABLE READ transaction isolation level:

    SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
    BEGIN TRANSACTION
    
        IF (EXISTS (SELECT * FROM myTable WHERE key=@key)
            UPDATE myTable SET ...
            WHERE key=@key
        ELSE
            INSERT INTO myTable (key, ...)
            VALUES (@key, ...)
    
    COMMIT TRANSACTION
    

    This isolation level will prevent/block subsequent repeatable read transactions from accessing same row (WHERE key=@key) while currently running transaction is open. On the other hand, operations on another row won't be blocked (WHERE key=@key2).

提交回复
热议问题