• I always use MERGE now rather than several IF blocks (unless I'm stuck with SQL2005 and earlier). It's important to test the merge before using it on live data though! I have a template I use with a hot-key to drop the basic structure into a new procedure. If you are new to MERGE you may not know that the DELETE/INSERT/UPDATE statements can be in different orders and each statement will accept any additional logic you want to apply.

    You can do all sorts of things like:

    ;MERGE INTO dbo.[TargetTable] AS [Target]

    USING (SELECT ID AS TargetTableID FROM dbo.[BookTable]) AS [Source]

    ON [Target].TargetTableID = [Source].TargetTableID

    WHEN MATCHED AND [Target].isDelete = 1

    THEN DELETE

    WHEN MATCHED AND NULLIF([Source].Title,'') IS NOT NULL

    THEN UPDATE

    SET

    [Target].Title = [Source].Title

    ,[Target].Text = [Source].Text

    WHEN NOT MATCHED BY TARGET AND NULLIF([Source].Title,'') IS NOT NULL

    THEN INSERT

    (

    Title

    ,Text

    )

    VALUES

    (

    [Source].Title

    ,[Source].Text

    )

    WHEN NOT MATCHED BY SOURCE AND YEAR([Target].DatePublished) < 2013

    THEN DELETE;