Search code examples
sqloracleinsert-updateon-duplicate-key

when matched update not working oracle merge


Here is something interesting! The merge statement works fine. But when the values match, it does not update the status to 'B' as expected. Any idea why?

merge into bbbt b 
using (select bank,ifsc,branch,
              center,district,state,
              address,status 
         from rtgbrn_temp 
        where ifsc in (SELECT ifsc 
                         FROM rtgbrn_temp 
                        MINUS 
                       SELECT ifsc_code 
                         FROM bbbt)
        ) x
   on (x.ifsc = b.ifsc_code)
 when matched then 
   update 
      set rtgs_stat = 'B' 
    where (x.ifsc=b.ifsc_code)
 when not matched then 
   insert (bankid,benbrn_code,brn_name,
           brn_addr,brn_loc,brn_stat,
           brn_city,coun_code,
           remarks,ifsc_code,
           rtgs_stat)
   values (substr(x.ifsc,1,4), substr(x.ifsc,5), 
           x.branch, x.address, x.district, 
           x.state, x.center,'IN', x.bank, x.ifsc,'R');

[also tried using the on duplicate update, but failed to work with an error]

SQL Error: ORA-00933: SQL command not properly ended!

insert into bbbt(bankid,benbrn_code,brn_name,brn_addr,brn_loc,brn_stat,brn_city,coun_code,remarks,ifsc_code,rtgs_stat)
select substr(x.ifsc,1,4), substr(x.ifsc,5), x.branch, x.address, x.district, x.state, x.center,'IN', x.bank, x.ifsc,'R' from 
(select bank,ifsc,branch,center,district,state,address,status from rtgbrn_temp where ifsc in (SELECT ifsc FROM rtgbrn_temp MINUS SELECT ifsc_code FROM bbbt))x
ON DUPLICATE KEY UPDATE rtgs_stat = 'B'; 

please share your knowledge, thanks!


Solution

  • Values from the query cannot match.

    Look carefully at this part of the query.

    select ..., ifsc, .....
    from rtgbrn_temp 
    where ifsc in (........
                   .........
                   MINUS 
                   SELECT ifsc_code 
                   FROM bbbt )
    

    This query retrieves ifsc codes that are not equal to any ifsc_code in bbbt table.

    Then the query uses these codes to match records:

     on (x.ifsc = b.ifsc_code)
    

    the above is eqivalent to

    on (subquery.ifsc = bbbt.ifsc_code)
    

    because x is an alias of the subquery, and b is the bbbt table name.

    Think a while ....
    The subquery returns only codes that are not equal to any value of bbbt.ifsc_code
    It means, that the condition subquery.ifsc = bbbt.ifsc_code never matches.