Oracle 12C 新特性之级联truncate

12c之前的版本中,在子表引用一个主表以及子表存在记录的情况下,是不提供截断此主表操作的。而在 12c 中的带有 CASCADE 操作的TRUNCATE TABLE 可以截断主表中的记录,并自动对子表进行递归截断,并作为 DELETE ON CASCADE 服从外键引用。由于这是应用到所有子表的,所以对递归层级的数量是没有 CAP 的,可以是孙子表或是重孙子表等等。这一增强摈弃了要在截断一个主表之前先截断所有子表记录的前提。新的 CASCADE 语句同样也可以应用到表分区和子表分区等。

SQL> 
create table parent(id number primary key);
create table child(cid number primary key,id number);
insert into parent values(1);
insert into parent values(2);
insert into child values(1,1);
insert into child values(2,1);
insert into child values(3,2);
commit;
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);
SQL> truncate table parent cascade;
ERROR at line 1:
ORA-14705: unique or primary keys referenced by enabled foreign keys in table
"C##ANDY"."CHILD"
-- 查看表约束
SQL> 
col CONSTRAINT_NAME for a25;
col TABLE_NAME for a25;
col COLUMN_NAME for a25;
select CONSTRAINT_NAME,TABLE_NAME, COLUMN_NAME from user_cons_columns where TABLE_NAME='CHILD';
CONSTRAINT_NAME           TABLE_NAME                COLUMN_NAME
------------------------- ------------------------- -------------------------
SYS_C007353               CHILD                     CID
FK_PARENT_CHILD           CHILD                     ID
-- 删除约束
SQL> alter table child drop constraint FK_PARENT_CHILD;
Table altered.
-- 添加约束,并附上 on delete cascade
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.

posted on 2017-05-12 12:54  张冲andy  阅读(527)  评论(0编辑  收藏  举报

导航