【Foreign Key】Oracle外來鍵約束三種刪除行為

路途中的人2012發表於2016-07-01
Oracle使用外來鍵來限制子表中參考的欄位值,要求子表中的資料必須在主表中存在。當主表的記錄發生變化時導致外來鍵參考唯一約束值發生了變化時,Oracle指定了三種動作:預設值(類似於restrict)、delete cascade和delete set null。
實際體驗一下他們對刪除操作的不同效果。

1.建立主表及子表並簡單初始化幾條資料
1)建立主表t_parent,並初始化三條記錄
sec@ora10g> create table t_parent (parent_id int primary key, name varchar2(10));
sec@ora10g> insert into t_parent values (1,'record1');
sec@ora10g> insert into t_parent values (2,'record2');
sec@ora10g> insert into t_parent values (3,'record3');
sec@ora10g> commit;

2)建立三種型別的子表t_child1、t_child2和t_child3
(1)no action型別
sec@ora10g> create table t_child1 (child1_id int primary key, parent_id int);
sec@ora10g> alter table t_child1 add constraint FK_t_child1 foreign key (parent_id) references t_parent (parent_id);
sec@ora10g> insert into t_child1 values (1,1);
sec@ora10g> commit;
(1)cascade型別
sec@ora10g> create table t_child2 (child2_id int primary key, parent_id int);
sec@ora10g> alter table t_child2 add constraint FK_t_child2 foreign key (parent_id) references t_parent (parent_id) on delete cascade;
sec@ora10g> insert into t_child2 values (2,2);
sec@ora10g> commit;
(1)set null型別
sec@ora10g> create table t_child3 (child2_id int primary key, parent_id int);
sec@ora10g> alter table t_child3 add constraint FK_t_child3 foreign key (parent_id) references t_parent (parent_id) on delete set null;
sec@ora10g> insert into t_child3 values (3,3);
sec@ora10g> commit;

2.確認主表和子表中的資料
sec@ora10g> select * from T_PARENT;

 PARENT_ID NAME
---------- ------------------------------
         1 record1
         2 record2
         3 record3

sec@ora10g> select * from T_CHILD1;

 CHILD1_ID  PARENT_ID
---------- ----------
         1          1

sec@ora10g> select * from T_CHILD2;

 CHILD2_ID  PARENT_ID
---------- ----------
         2          2

sec@ora10g> select * from T_CHILD3;

 CHILD2_ID  PARENT_ID
---------- ----------
         3          3

3.嘗試對具有預設型別外來鍵參照的主表記錄進行刪除
sec@ora10g> delete from T_PARENT where parent_id = 1;
delete from T_PARENT where parent_id = 1
*
ERROR at line 1:
ORA-02292: integrity constraint (SEC.FK_T_CHILD1) violated - child record found

sec@ora10g> select * from T_CHILD1;

 CHILD1_ID  PARENT_ID
---------- ----------
         1          1

在此型別下,不允許刪除。

4.嘗試對具有delete cascade型別外來鍵參照的主表記錄進行刪除
sec@ora10g> delete from T_PARENT where parent_id = 2;

1 row deleted.

sec@ora10g> select * from T_CHILD2;

no rows selected

成功,級聯刪除成功。

5.嘗試對具有delete set null型別外來鍵參照的主表記錄進行刪除
sec@ora10g> delete from T_PARENT where parent_id = 3;

1 row deleted.

sec@ora10g> select * from T_CHILD3;

 CHILD2_ID  PARENT_ID
---------- ----------
         3

主表記錄可以完成刪除,子表中對應的內容被設定為NULL。

6.小結
以上就是在Oracle資料庫,當主表資訊刪除後對應的子表中記錄的三種不同的處理方式,針對具體的應用場合請選擇合適型別。

Good luck.

secooler
10.03.21

-- The End --

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29067253/viewspace-2121353/,如需轉載,請註明出處,否則將追究法律責任。

相關文章