Solutions for INSERT OR UPDATE on SQL Server

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

    If going the UPDATE if-no-rows-updated then INSERT route, consider doing the INSERT first to prevent a race condition (assuming no intervening DELETE)

    INSERT INTO MyTable (Key, FieldA)
       SELECT @Key, @FieldA
       WHERE NOT EXISTS
       (
           SELECT *
           FROM  MyTable
           WHERE Key = @Key
       )
    IF @@ROWCOUNT = 0
    BEGIN
       UPDATE MyTable
       SET FieldA=@FieldA
       WHERE Key=@Key
       IF @@ROWCOUNT = 0
       ... record was deleted, consider looping to re-run the INSERT, or RAISERROR ...
    END
    

    Apart from avoiding a race condition, if in most cases the record will already exist then this will cause the INSERT to fail, wasting CPU.

    Using MERGE probably preferable for SQL2008 onwards.

提交回复
热议问题