外鍵約束保證參照完整性
下面我們創建一張參照表
CREATE TABLE state_lookup
(state VARCHAR
state_desc VARCHAR
ALTER TABLE state_lookup
ADD CONSTRAINT pk_state_lookup PRIMARY KEY (state)
USING INDEX TABLESPACE student_index;
然後插入幾行記錄
INSERT INTO state_lookup VALUES (
INSERT INTO state_lookup VALUES (
INSERT INTO state_lookup VALUES (
我們通過實現父子關系來保證參照完整性
|State_lookup | 是State字段
| 這個例子中
| 它是一個主鍵字段(參看DDL)
/|\
| Students |
上圖顯示了State_Lookup表和Students表間一對多的關系
State_Lookup表中的一個州名可以在Students表中出現多次
外鍵同時保證Students表中State字段的完整性
外鍵約束創建在子表
CREATE TABLE students
(student_id VARCHAR
student_name VARCHAR
college_major VARCHAR
status VARCHAR
state VARCHAR
license_no VARCHAR
ALTER TABLE students
ADD CONSTRAINT pk_students PRIMARY KEY (student_id)
USING INDEX TABLESPACE student_index;
ALTER TABLE students
ADD CONSTRAINT uk_students_license
UNIQUE (state
USING INDEX TABLESPACE student_index;
ALTER TABLE students
ADD CONSTRAINT ck_students_st_lic
CHECK ((state IS NULL AND license_no IS NULL) OR
(state IS NOT NULL AND license_no is NOT NULL));
ALTER TABLE students
ADD CONSTRAINT fk_students_state
FOREIGN KEY (state) REFERENCES state_lookup (state);
一
參照完整性規則在父表更新刪除期間和子表插入更新期間強制執行
PARENT
CHILD
下面示例說明四種錯誤類型
測試表結構及測試數據如下
STATE_LOOKUP
State State Description
CA California
NY New York
NC North Carolina
STUDENTS
Student ID Student Name College Major Status State License NO
A
A
A
A
A
SQL> UPDATE state_lookup
UPDATE state_lookup
*
ERROR at line
ORA
violated 每 child record found
SQL> DELETE FROM state_lookup
DELETE FROM state_lookup
*
ERROR at line
ORA
violated 每 child record found
SQL> INSERT INTO STUDENTS
INSERT INTO STUDENTS
*
ERROR at line
ORA
violated
SQL> UPDATE students
UPDATE students
*
ERROR at line
ORA
violated
上面四種類型錯誤都有一個同樣的錯誤代碼
參照完整性是數據庫設計的關鍵一部分
二
外鍵語法有個選項可以指定級聯刪除特征
使用這個選項
使用創建外鍵約束的DELETE CASCADE選項
ALTER TABLE students
ADD CONSTRAINT fk_students_state
FOREIGN KEY (state) REFERENCES state_lookup (state)
ON DELETE CASCADE;
執行刪除語句
DELETE FROM state_lookup WHERE state =
然後再查詢students表中的數據
如果表間有外鍵關聯
定義一個級聯刪除時需要考慮下面問題
如果不能級聯刪除
ALTER TABLE students
ADD CONSTRAINT fk_students_state
FOREIGN KEY (state) REFERENCES state_lookup (state)
ON DELETE SET NULL;
三
創建外鍵約束是
如果外鍵字段參照的是Unique而非Primary Key字段
四
外鍵約束可以在不同用戶模式及不同數據庫實例間應用
From:http://tw.wingwit.com/Article/program/Oracle/201311/17654.html