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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With