Solutions for INSERT OR UPDATE on SQL Server

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

    Although its pretty late to comment on this I want to add a more complete example using MERGE.

    Such Insert+Update statements are usually called "Upsert" statements and can be implemented using MERGE in SQL Server.

    A very good example is given here: http://weblogs.sqlteam.com/dang/archive/2009/01/31/UPSERT-Race-Condition-With-MERGE.aspx

    The above explains locking and concurrency scenarios as well.

    I will be quoting the same for reference:

    ALTER PROCEDURE dbo.Merge_Foo2
          @ID int
    AS
    
    SET NOCOUNT, XACT_ABORT ON;
    
    MERGE dbo.Foo2 WITH (HOLDLOCK) AS f
    USING (SELECT @ID AS ID) AS new_foo
          ON f.ID = new_foo.ID
    WHEN MATCHED THEN
        UPDATE
                SET f.UpdateSpid = @@SPID,
                UpdateTime = SYSDATETIME()
    WHEN NOT MATCHED THEN
        INSERT
          (
                ID,
                InsertSpid,
                InsertTime
          )
        VALUES
          (
                new_foo.ID,
                @@SPID,
                SYSDATETIME()
          );
    
    RETURN @@ERROR;
    

提交回复
热议问题