2024年5月7日发(作者:amd显卡和nvidia显卡)
Oracle数据库中Constraint约束的四对属性
在创建数据库的时候会创建一些Constraint约束,包括主键、外键等。那么约束它有属性吗?
答案是肯定的,介绍一下Oracle数据库Constraint约束的四对属性:Deferrable/not deferrable,
Deferred/immediate, enalbe/disable, validate/novalidate。
able,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)这对属性是在创建的constraint的时候定义的,不能被修改.
(4)notice:如果建立了Deferrable的uk或pk,只会建立相应的nonuniquce index,而不会建立
uniquce index
ed,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是否对表中已经存在的数据作检查,例如:
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数据时还是要作唯一性检查的),在enable时重建索引.
Disbale deferrable 的pk、uk将保留原来的索引(因为原来的索引就是非唯一性的,不影响insert
的操作).
(3) 一些操作经验:
KEEP INDEX要注意的:
TABLE games DISAble CONSTRAINT fk_num keep index;--唯一索引被保留,所以还
是不能插入重复的数据.不应该keep index.
TABLE games DISAble CONSTRAINT fk_num;--如果上一步被执行,那么此语句什
么都不做,唯一索引仍被保留,此时应该先enable在disable.如果原来的状态是able的话,那么
唯一索引将被删除.
发布者:admin,转转请注明出处:http://www.yc00.com/num/1715078336a2562539.html
评论列表(0条)