加入收藏 | 设为首页 | 会员中心 | 我要投稿 源码网 (https://www.900php.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql – 从父表和子表中删除行

发布时间:2021-01-18 21:33:58 所属栏目:MsSql教程 来源:网络整理
导读:假设Oracle 10G中有两个表 TableA (Parent) -- TableB (Child) TableA中的每一行都有几个与它相关的子行. 我想删除TableA中的特定行,这意味着我必须首先删除tableB中的相关行. 这会删除子条目 delete from tableB where last_update_Dtm = sysdate-30; 要

假设Oracle 10G中有两个表

TableA (Parent) --> TableB (Child)

TableA中的每一行都有几个与它相关的子行.

我想删除TableA中的特定行,这意味着我必须首先删除tableB中的相关行.

这会删除子条目

delete from tableB where last_update_Dtm = sysdate-30;

要删除子表中刚刚删除的行的父行,我可以这样做

Delete from TableA where not exists (select 1 from tableB where tableA.key=tableB.key);

以上内容还将删除子表中的行(last_update_Dtm = sysdate-30)为false. TableA没有last_update_dtm列,因此如果没有子表中的条目,则无法知道要删除哪些行.

我可以在删除之前将密钥保存在子表中,但这似乎是一种昂贵的方法.删除两个表中的行的正确方法是什么?

编辑

为了更好地解释我想要实现的目标,如果两个表之间没有约束,以下查询将完成我想要做的事情.

Delete from tableA
Where exists (
Select 1 from tableB
where tableA.key=tableB.key
and tableB.last_update_dtm=sysdate-30)

Delete from tableB where last_update_dtm=systdate-30

解决方法

两种可能的方法.

>如果您有外键,请将其声明为on-delete-cascade并删除超过30天的父行.将自动删除所有子行.
>根据您的描述,您似乎知道要删除的父行,并且需要删除相应的子行.你试过像这样的SQL吗?

delete from child_table
      where parent_id in (
           select parent_id from parent_table
                where updd_tms != (sysdate-30)

– 现在删除父表记录

delete from parent_table
where updd_tms != (sysdate-30);

—-根据您的要求,您可能不得不使用PL / SQL.我会看看是否有人可以发布一个纯SQL解决方案(在这种情况下肯定会是这样).

declare
    v_sqlcode number;
    PRAGMA EXCEPTION_INIT(foreign_key_violated,-02291);
begin
    for v_rec in (select parent_id,child id from child_table
                         where updd_tms != (sysdate-30) ) loop

    -- delete the children
    delete from child_table where child_id = v_rec.child_id;

    -- delete the parent. If we get foreign key violation,-- stop this step and continue the loop
    begin
       delete from parent_table
          where parent_id = v_rec.parent_id;
    exception
       when foreign_key_violated
         then null;
    end;
 end loop;
end;
/

(编辑:源码网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读