Solutions for INSERT OR UPDATE on SQL Server

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

    That depends on the usage pattern. One has to look at the usage big picture without getting lost in the details. For example, if the usage pattern is 99% updates after the record has been created, then the 'UPSERT' is the best solution.

    After the first insert (hit), it will be all single statement updates, no ifs or buts. The 'where' condition on the insert is necessary otherwise it will insert duplicates, and you don't want to deal with locking.

    UPDATE  SET =@field WHERE key=@key;
    
    IF @@ROWCOUNT = 0
    BEGIN
       INSERT INTO  (field)
       SELECT @field
       WHERE NOT EXISTS (select * from tableName where key = @key);
    END
    

提交回复
热议问题