級聯truncate

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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章