Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server 2008 Merge Statement Multiple Match Conditions

I am attempting to bring in claim data in an incremental manner. I am matching source and target on System (varchar) and ClaimNum (varchar), with a hash of the other columns to check for changes.

I have my merge statement (simplified):

MERGE target
USING source ON target.System = source.System
             AND target.ClaimNum = source.ClaimNum

WHEN MATCHED AND target.HashValue <> source.HashValue
THEN {update claim record data}

WHEN MATCHED AND target.HashValue = source.HashValue
THEN {update claim record as "checked"}

WHEN NOT MATCHED
THEN {insert new claim record}

However, I can't have 2 matched conditions. How else can I accomplish this with a merge statement?

This is being used on SQL Server 2008.

like image 746
wk4997 Avatar asked Jul 25 '16 18:07

wk4997


People also ask

How many when matched clauses can be used in a MERGE statement?

The MERGE statement can have, at most, two WHEN MATCHED clauses. If two clauses are specified, the first clause must be accompanied by an AND <search_condition> clause. For any given row, the second WHEN MATCHED clause is only applied if the first isn't.

Can we use with clause in MERGE statement?

At most, we can specify only two WHEN MATCHED clauses in the MERGE statement. If two WHEN MATCHED clauses are specified, one clause must have an update operation and the other one must use delete operation.

Can we use CTE in MERGE statement?

Multiple CTE query definitions can be defined in a CTE. A CTE must be followed by a single SELECT statement. INSERT , UPDATE , DELETE , and MERGE statements aren't supported.


1 Answers

You could use CASE or IIF(SQL Server 2012) to add custom logic:

MERGE target
USING source
  ON target.System = source.System
 AND target.ClaimNum = source.ClaimNum
WHEN MATCHED THEN 
   UPDATE SET column_name = 
            CASE WHEN target.HashValue = source.HashValue THEN ...
                 ELSE ...
            END
WHEN NOT MATCHED THEN {insert new claim record}

EDIT:

If it is only UPDATE you could use multiple conditions/set to the same value to skip:

...
UPDATE SET column_name1 = 
            CASE WHEN condition1 THEN ...
                 ELSE column_name1
            END
           ,column_name2 = 
             CASE WHEN condition1 THEN ...
                  WHEN condition2 THEN ...
                  ELSE column_name2
             END
           ,...

Note:

If source/target HashValue is nullable you should handle it using COALESCE/ISNULL/adding OR target.HashValue IS NULL.... Comparison operators don't work with NULL.

like image 89
Lukasz Szozda Avatar answered Sep 18 '22 19:09

Lukasz Szozda