Solutions for INSERT OR UPDATE on SQL Server

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

    I had tried below solution and it works for me, when concurrent request for insert statement occurs.

    begin tran
    if exists (select * from table with (updlock,serializable) where key = @key)
    begin
       update table set ...
       where key = @key
    end
    else
    begin
       insert table (key, ...)
       values (@key, ...)
    end
    commit tran
    

提交回复
热议问题