How to implement a conditional Upsert stored procedure?

后端 未结 5 1380
闹比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:15

    CREATE PROCEDURE [dbo].[usp_UpsertItem] -- Add the parameters for the stored procedure here @pContentID varchar(30) = null, @pTitle varchar(255) = null, @pTeaser varchar(255) = null AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON;

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

    END

提交回复
热议问题