Creating a merge that contains an IF condition

  • astrid 69000

    Hall of Fame

    Points: 3154

    Hi,

    want to merge two tables on two columns, partid and serialid.

    but then I want to check if the purchasedate also match, if it matches I leave it alone, otherwise I update the date and source. i having having issues with the if part.

    MERGE [dbo].[tableone] T
    USING [dbo].tabletwo S
    ON (S.PARTID = T.PART_ID AND S.SERIAL = T.SERIAL)
    WHEN MATCHED
    --i would like to check here if the dates also match
    -- do nothing
    -- if they dont then update
    THEN UPDATE SET
    T.DATE = S.DATE...
    ---and then otherwise insert.
  • Phil Parkin

    SSC Guru

    Points: 244801

    Have you tried something like this? The HOLDLOCK helps avoid potential concurrency issues.

    MERGE [dbo].[tableone] WITH (HOLDLOCK) T
    USING [dbo].tabletwo S
    ON (S.PARTID = T.PART_ID AND S.SERIAL = T.SERIAL)
    WHEN MATCHED AND (S.DATE <> T.DATE or T.DATE IS NULL)
    THEN UPDATE SET
    T.DATE = S.DATE...
    ---and then otherwise insert.

    If the answer to your question can be found with a brief Google search, please perform the search yourself, rather than expecting one of the SSC members to do it for you.
    See https://www.sqlservercentral.com/articles/forum-etiquette-how-to-post-datacode-on-a-forum-to-get-the-best-help/ for details of how to post T-SQL code-related questions.

  • astrid 69000

    Hall of Fame

    Points: 3154

    thanks

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic. Login to reply