12c之前的版本中,在子表引用一个主表以及子表存在记录的情况下,是不提供截断此主表操作的。而在 12c 中的带有 CASCADE 操作的TRUNCATE TABLE 可以截断主表中的记录,并自动对子表进行递归截断,并作为 DELETE ON CASCADE 服从外键引用。由于这是应用到所有子表的,所以对递归层级的数量是没有 CAP 的,可以是孙子表或是重孙子表等等。这一增强摈弃了要在截断一个主表之前先截断所有子表记录的前提。新的 CASCADE 语句同样也可以应用到表分区和子表分区等。
SQL> create table parent(id number primary key);
Table created.
SQL> create table child(cid number primary key,id number);
Table created.
SQL> insert into parent values(1);
1 row created.
SQL> insert into parent values(2);
1 row created.
SQL> insert into child values(1,1);
1 row created.
SQL> insert into child values(2,1);
1 row created.
SQL> insert into child values(3,2);
1 row created.
SQL> commit;
Commit complete.
SQL> select a.id,b.cid,b.id from parent a, child b where a.id=b.id;
ID CID ID
1 1 1
1 2 1
2 3 2
--添加约束,不附上 on delete cascade
SQL> alter table child add constraint fk_parent_child foreign key(id) references parent(id);
Table altered.
SQL> truncate table parent cascade;
truncate table parent cascade
*
ERROR at line 1:
ORA-14705: unique or primary keys referenced by enabled foreign keys in table
"HR"."CHILD"
SQL> col CONSTRAINT_NAME for a25;
SQL> col TABLE_NAME for a25;
SQL> col COLUMN_NAME for a25;
SQL> select CONSTRAINT_NAME,TABLE_NAME, COLUMN_NAME from user_cons_columns where TABLE_NAME='CHILD';
CONSTRAINT_NAME TABLE_NAME COLUMN_NAME
SYS_C0010458 CHILD CID
FK_PARENT_CHILD CHILD ID
-- 删除并添加约束,并附上 on delete cascade
SQL> alter table child drop constraint FK_PARENT_CHILD;
Table altered.
SQL> alter table child add constraint fk2_parent_child foreign key(id) references parent(id) on delete cascade;
Table altered.
SQL> truncate table parent cascade;
Table truncated.
SQL> select a.id,b.cid,b.id from parent a, child b where a.id=b.id;
no rows selected