Oracle數(shù)據(jù)庫中Constraint約束的四對屬性
我們在創(chuàng)建數(shù)據(jù)庫的時候會創(chuàng)建一些Constraint約束,包括主鍵、外鍵等。那么約束它有屬性嗎?答案是肯定的,本文我們就介紹一下Oracle數(shù)據(jù)庫Constraint約束的四對屬性:Deferrable/not deferrable, Deferred/immediate, enalbe/disable, validate/novalidate,接下來就讓我們來一起了解一下這一過程吧。
1.Deferrable,not deferrable(default value)
1)這對屬性是定義是否可以defer,defer是指作檢查的時機,如果在commit的時check為Defer,否則為immediate .只有在設置Deferrable才可以設置另一個屬性2-- Deferred,immediate.
2)設置defer check的方法有兩種(前提是建立了Deferrable的contraint)
a.通過建contraint時指定Deferred值
b.通過會話級別的語句修改
SET CONSTRAINT(s) contraint_name/all immediate/deferred.
3)這對屬性是在創(chuàng)建的constraint的時候定義的,不能被修改.
4)notice:如果建立了Deferrable的uk或pk,只會建立相應的nonuniquce index,而不會建立uniquce index
2.Deferred,immediate(default value)
1)這對屬性定義是否defer. Deferred: check on commit; immediate: check immediate.
2)If constraint is not deferrable,immediate is only choice.
3) For example:
- CREATE TABLE games
- (scores NUMBER, CONSTRAINT unq_num UNIQUE (scores)
- INITIALLY DEFERRED DEFERRABLE);
- insert into games values(1);
- insert into games values(1);
- commit;--在此報錯
- You will not get a error util you commit it;
- SET CONSTRAINT(s) unq_num immediate;--修改屬性
- insert into games values(2);
- insert into games values(2);--在此報錯
- commit;
- You will get a error when you execute the second sql;
3. novalidate, validate(default value)
1) 這對屬性定義constraint是否對表中已經(jīng)存在的數(shù)據(jù)作檢查,例如:
- create table t(id number);
- insert into t values(1);
- insert into t values(2);
- alter table t add constraint ch_100 check(id>=100); --失敗
- alter table t add constraint ch_100 check(id>=100) novalidate;--成功
2) notice:與唯一索引相關的contraint(例如pk,uk),要做到以上的效果還必須設置為Deferrable(只是建立非唯一性索引),因為在維護索引是,如果違反了唯一性也會報錯,所以必須建立非唯一性索引.例如:
- drop table t;
- create table t(id number);
- insert into t values(1);
- insert into t values(1);
- alter table t add constraint ch_100 unique(id) ; --報錯
- alter table t add constraint ch_100 unique(id) novalidate; --報錯
- alter table t add constraint ch_100 unique(id) deferrable novalidate;--成功
4. disable, enalbe(default value)
1) 啟用和禁用constraint.在新建pk和uk時定義了disable,將不建立相應的索引.
- ALTER TABLE dept DISABLE CONSTRAINT dname_ukey;
- ALTER TABLE dept ENABLE CONSTRAINT dname_ukey;
- alter table t add constraint ch_100 unique(id) disable;
2) DISABLE uk或pk作了些什么:
Disable非deferrable 的pk、uk,將刪除相應的索引(除非指定了keep index,但是keep下來的索引是唯一性的,insert數(shù)據(jù)時還是要作唯一性檢查的),在enable時重建索引.
Disbale deferrable 的pk、uk將保留原來的索引(因為原來的索引就是非唯一性的,不影響insert的操作).
3) 一些操作經(jīng)驗:
KEEP INDEX要注意的:
a.ALTER TABLE games DISAble CONSTRAINT fk_num keep index;--唯一索引被保留,所以還是不能插入重復的數(shù)據(jù).不應該keep index.
b.ALTER TABLE games DISAble CONSTRAINT fk_num;--如果上一步被執(zhí)行,那么此語句什么都不做,唯一索引仍被保留,此時應該先enable在disable.如果原來的狀態(tài)是able的話,那么唯一索引將被刪除.
關于Oracle數(shù)據(jù)庫constraint約束的四對屬性的知識就介紹到這里了,希望本次的介紹能夠?qū)δ兴斋@!
【編輯推薦】