从 PL/SQL 过程块中删除

DELETE FROM inside a PL/SQL Procedure Block

我目前正在尝试删除通过外键链接到另一行的 table 的所有行。

我的代码看起来有点像这样:

CREATE OR REPLACE Procedure test
BEGIN
   DELETE FROM person;
End;
/

错误显示:违反了 ora-02292 完整性约束 - 找到子记录

当我尝试禁用约束时,它说我不能 'ALTER' table。

我需要做什么 do/change?

你不应该只是禁用约束,因为你会留下child记录孤儿(没有parent 为他们记录)。那你会怎么做?

正确的处理方式是

  • 先删child仁
  • 删除parent最后

如果使用 on delete cascade 选项创建外键约束,数据库会为您处理。


P.S。从“您不能更改 table”开始——这不是 Oracle 错误消息。他们有自己的代码,例如ORA-06550。很难猜测您实际做了什么,并且 - 如果我不得不猜测 - 我会说您试图在程序中这样做:

SQL> create table temp (id number constraint pkt primary key);

Table created.

SQL> begin
  2    alter table temp disable constraint pkt;
  3  end;
  4  /
  alter table temp disable constraint pkt;
  *
ERROR at line 2:
ORA-06550: line 2, column 3:
PLS-00103: Encountered the symbol "ALTER" when expecting one of the following:
( begin case declare exit for goto if loop mod null pragma
raise return select update while with <an identifier>
<a double-quoted delimited-identifier> <a bind variable> <<
continue close current delete fetch lock insert open rollback
savepoint set sql execute commit forall merge pipe purge

您需要动态 SQL 才能做到这一点:

SQL> begin
  2    execute immediate 'alter table temp disable constraint pkt';
  3  end;
  4  /

PL/SQL procedure successfully completed.

SQL>

但是,再说一次,这不是您处理这种情况的方式。