Delete a child and a parent row with one SQL script

前端 未结 7 612
执念已碎
执念已碎 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:57

    If you always want to delete the children when you delete a parent row, you can declare the foreign key constraint so that Oracle does the child delete automatically

    create table parent (
      parentID number primary key,
      parentData varchar2(100)
    );
    
    create table child (
      childID number primary key,
      parentID number references parent( parentID ) on delete cascade,
      childData varchar2(100)
    );
    

    for example, will declare a parent table and a child table and automatically delete the child rows when you delete the parent row. If you don't want that sort of thing to be enforced automatically or you don't like the complexity that is added when things happen "automagically" in the background, you're probably stuck with using multiple DELETE statements.

    0 讨论(0)
提交回复
热议问题