简体   繁体   中英

DELETE and INSERT using MERGE statement in ORACLE

I have entity Employee, and it has a field List<String> accountIds.

so table structure looks like this:

CREATE TABLE EMPLOYEE (
ID varchar2(255) not null,
OBJ_ID varchar2(36), 
NAME varchar2(255),
VER_NBR number(19,0),
CREATEID varchar2(255) not null,
CREATETIME timestamp (6) not null,
UPDATEID varchar2(255),
UPDATETIME timestamp (6),
primary key (ID));

and to store AccountIds I've another table

CREATE TABLE EMPLOYEE_ACCOUNT_IDS(
        EMP_ID varchar2(255),
        ACC_ID varchar2(255),
        primary key (EMP_ID, ACC_ID)
);

Update operation : ACCOUNT_IDS in EMPLOYEE table

Right now, in the application I'm deleting all the accountids related to the employee and re-insert all.

To improve performance and reduce the number of db queries. Is this possible to do with "MERGE" STATEMENT.

Yep. It is possible, not sure if faster then delete and insert. I don't know how your input looks like, so it would be nice how do you perform insert. Anyway you can make join of existing data and new values and use this query as source table.

merge into employee_account_ids tgt
using (  
  with new_data(acc_id) as (select * from table(sys.odcivarchar2list('NEW01', 'NEW02', 'ACC13')))
    select '001' emp_id, nvl(a.acc_id, n.acc_id) acc_id, rwd,
           case when n.acc_id is null then 'del' end dsc
      from new_data n 
      full join (select e.*, rowid rwd from employee_account_ids e where emp_id = '001') a 
        on a.acc_id = n.acc_id ) src
on (src.emp_id = tgt.emp_id and src.rwd = tgt.rowid)
when matched then update set tgt.acc_id = tgt.acc_id delete where dsc = 'del'
when not matched then insert values (src.emp_id, src.acc_id)

dbfiddle

The problem is your second table has no dummy column which I could touch to perform delete, because Oracle requires update first to delete row. So I used rowid, cheated update ( tgt.acc_id = tgt.acc_id ) and it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM