如何在Oracle中用非默認(rèn)方式創(chuàng)建外鍵
導(dǎo)讀:oracle數(shù)據(jù)庫是一種功能性很好的數(shù)據(jù)庫系統(tǒng),在數(shù)據(jù)庫=業(yè)界也是占據(jù)著重要地位的,相信很多人對oracle數(shù)據(jù)庫都是比較熟悉的,可是對與在oracle數(shù)據(jù)庫中用非默認(rèn)方式創(chuàng)建外鍵大家未必都會,下文就教給大家如何在oracle數(shù)據(jù)庫中用非默認(rèn)方式創(chuàng)建外鍵。
創(chuàng)建外鍵約束時(shí)如果使用Oracle默認(rèn)的創(chuàng)建方式,在刪除被參照的數(shù)據(jù)時(shí),將無法被刪除,這一點(diǎn)在Oracle9i中給了我們更多靈活的選擇,我們可是使用on delete cascade和 on delete set null關(guān)鍵字來決定刪除被參照數(shù)據(jù)時(shí)是否要將參照這個(gè)數(shù)據(jù)的那些數(shù)據(jù)一并刪除,還是將那些參照這條數(shù)據(jù)的數(shù)據(jù)的對應(yīng)值賦空。
例如下面這兩個(gè)表中分別存的時(shí)員工的基本信息和公司的部門信息。我們?yōu)?/p>
create table dept
(deptno number(10) not null,
deptname varchar2(30) not null,
constraint pk_dept primary key(deptno));
和
create table emp
( empno number(10) not null,
fname varchar2(20) ,
lname varchar2(20) ,
dept number(10) ,
constraint pk_emp primary key(empno));
然后我們現(xiàn)在分別使用這兩個(gè)關(guān)鍵字來增加外鍵試一下,首先我們來試一下on delete cascade
alter table emp
add constraint fk_emp_dept foreign key(dept) references dept(deptno) on delete cascade;
先增加外鍵。然后插入數(shù)據(jù)。
insert into dept values(1,’銷售部’);
insert into dept values(2,’財(cái)務(wù)部’);
insert into emp values (2,’Mary’,'Song’,1);
insert into emp values (3,’Linda’,'Liu’,2);
insert into emp values (4,’Linlin’,'Zhang’,1);
然后現(xiàn)在我要?jiǎng)h除銷售部,會有什么后果呢?
delete from dept where deptno = 1;
我們發(fā)現(xiàn)除了dept中的一條數(shù)據(jù)被刪除了,emp中兩條數(shù)據(jù)也被刪除了,其中emp中的兩條數(shù)據(jù)是參照了銷售部的這條數(shù)據(jù)的,這就很容易理解on delete cascade了。
創(chuàng)建外鍵約束時(shí)如果使用Oracle默認(rèn)的創(chuàng)建方式,在刪除被參照的數(shù)據(jù)時(shí),將無法被刪除,這一點(diǎn)在Oracle9i中給了我們更多靈活的選擇,我們可是使用on delete cascade和 on delete set null關(guān)鍵字來決定刪除被參照數(shù)據(jù)時(shí)是否要將參照這個(gè)數(shù)據(jù)的那些數(shù)據(jù)一并刪除,還是將那些參照這條數(shù)據(jù)的數(shù)據(jù)的對應(yīng)值賦空。
按照上文中介紹的就能夠?qū)崿F(xiàn)在oracle數(shù)據(jù)庫中用非默認(rèn)方式創(chuàng)建外鍵的目的,希望對大家能夠有所幫助。
【編輯推薦】