[ CONSTRAINT constraint_name ] { NOT NULL | NULL | CHECK ( expression ) [ NO INHERIT ] | DEFAULT default_expr | UNIQUE index_parameters | PRIMARY KEY index_parameters | REFERENCES reftable [ ( refcolumn ) ] [ MATCH FULL | MATCH PARTIAL | MATCH SIMPLE ] [ ON DELETE action ] [ ON UPDATE action ] } [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
DEFERRABLE(可以推迟的约束检查):可以推迟到事务结尾。目前仅UNIQUE, PRIMARY KEY, EXCLUDE和FOREIGN KEY才支持DEFERRABLE。NOT NULL和CHECK约束不支持。
NOT DEFERRABLE(不可推迟的约束检查):在每一个命令后会立即验证是否满足约束条件。缺省是NOT DEFERRABLE。
如果约束是INITIALLY IMMEDIATE,那么每条语句之后就检查它。这个是缺省。
如果约束是INITIALLY DEFERRED,那么直到事务完成才检查。
检查的时间可以用以下命令修改:
SET CONSTRAINTS [ DEFERRABLE | NOT DEFERRABLE ] [ INITIALLY DEFERRED | INITIALLY IMMEDIATE ]
例子:
- 默认是NOT DEFERRABLE INITIALLY IMMEDIATE
create table t1 (id number, name char(10));
alter table t1 modify id number primary key;
SQL> insert into t1 values(1,'Tough1'); 已创建 1 行。
SQL> insert into t1 values(1,'Tough1'); insert into t1 values(1,'Tough1') * 第 1 行出现错误: ORA-00001: 违反唯一约束条件 (SCOTT.SYS_C005428)
- DEFERRABLE或INITIALLY DEFERRED的情况:
create table t2 (id number, name char(10));
alter table t2 modify id number primary key INITIALLY DEFERRED;
或
alter table t2 modify id number primary key DEFERRABLE INITIALLY DEFERRED;
SQL> insert into t2 values(1,'Tough1');
已创建 1 行。
SQL> insert into t2 values(1,'Tough1');
已创建 1 行。
SQL> commit; commit * 第 1 行出现错误: ORA-02091: 事务处理已回退 ORA-00001: 违反唯一约束条件 (SCOTT.SYS_C005435)