How to implement a conditional Upsert stored procedure?

后端 未结 5 1459
闹比i
闹比i 2021-02-06 10:49

I\'m trying to implement your basic UPSERT functionality, but with a twist: sometimes I don\'t want to actually update an existing row.

Essentially I\'m trying to synchr

5条回答
  •  耶瑟儿~
    2021-02-06 11:17

    BEGIN TRANSACTION
    
    IF EXISTS(SELECT 1 FROM dbo.Item WHERE ContentID = @pContentID)
         UPDATE dbo.Item WITH (SERIALIZABLE)
         SET Title = @pTitle, Teaser = @pTeaser
         WHERE ContentID = @pContentID
         AND RowLocked = false
    ELSE
         INSERT INTO dbo.Item
              (ContentID, Title, Teaser)
         VALUES
              (@pContentID, @pTitle, @pTeaser)
    
    COMMIT TRANSACTION
    

提交回复
热议问题