Delete a child and a parent row with one SQL script

前端 未结 7 610
执念已碎
执念已碎 2021-01-04 00:30

Instead of deleting the child row and then writing another sql statement to delete the parent row I wanted to use one statement which will do both. FYI: we use Oracle databa

7条回答
  •  醉梦人生
    2021-01-04 00:52

    You can only do it badly - i.e., using triggers.

    create table parent
    (pid number,
       constraint parent_pk
         primary key (pid)
         using index
    );
    
    create table child
      (cid number,
       pid number,
       constraint child_pk
         primary key(cid)
         using index,
       constraint child_fk
         foreign key (pid)
         references parent (pid)
      );
    
    create index child_fk on child (pid);
    
    create trigger fake_delete_cascade
    before delete on parent
    for each row
    begin
      delete from child where pid = :old.pid;
    end;
    /
    
    insert into parent values (1);
    insert into child values (1,1);
    commit;
    select count(*) from child;
    delete from parent where pid = 1;
    select count(*) from child;
    

提交回复
热议问题