Overcome SQL MERGE Failure

Viewed 36

I am trying to update the customer old values with new values. I need some suggestions in handling the update.

TEMP_TABLE has the below data

ORDER_ID CUSTOMER_NAME OLD_VALUE NEW_VALUE
1 Sam ABC DEF
1 Sam ABC GHI
2 Sam ABC DEF
2 Sam ABC GHI
3 Sam ABC DEF
3 Sam ABC GHI

I am using the below MERGE statement for updating these values into the TARGET_TABLE

merge into target_table tt
using (
          select distinct order_id, old_value, new_value
            from test_table 
       )
 test on (test.order_id= tt.order_id)
 when matched then 
 update set tt.old_value= test.new_value;

This MERGE statement will fail with unstable set of records, since each ORDER_ID has 2 NEW_VALUEs.

I can use a max(NEW_VALUE) and proceed with the update. But the requirement is as below:

  1. For ORDER_ID = 1; the NEW_VALUE can be updated to DEF or GHI
  2. For ORDER_ID = 2; the NEW_VALUE shouldn't be same NEW_VALUE as ORDER_ID = 1. If ORDER_ID=1 NEW_VALUE was updated to DEF then ORDER_ID = 2 should get updated with GHI
  3. For ORDER_ID = 3; it could be either of the 2 NEW_VALUEs.

Need suggestions on how to handle such scenarios

0 Answers
Related