SlideShare uma empresa Scribd logo
1 de 18
Baixar para ler offline
Oracle 的 Constraint 约束
                        Zianed Hou

                       zianed@live.cn




1、constraint类型介绍
2、constraint的创建和管理
   第一种ENABLED、VALIDATED
   第二种DISABLED、NOT VALIDATED
   第三种EBABLED、NOT VALIDATED
   第四种DISABLED、VALIDATED
3、constraint的种类
   3.1、CHECK约束
   3.2、NOT NULL约束
   3.3、Unique约束
   3.4、Primary Key约束
   3.5、Foreign Key约束
4、延迟约束检查




Zianed                    Version 1.1   1
1、constraint类型介绍
SQL> select distinct constraint_type from dba_constraints;

CONSTRAINT_TYPE
-
V
R
U
P
?
C
O

已选择 7 行。
SQL>

类型说明:
V——(Check Option on a view)
R——(Reference Froeign Key 参照外键约束
U——(Unique)唯一性约束
P——(Primary Key)unique and not null,主键约束
?——
C——(Check)present in a static list of values permitted for the column,检查约束
O——(Read Only on a view)
描述:
Type.Code Type .Description           Acts.On.Level
C Check.on.a.table        Column
O Read.Only.on.a.view           Object
P Primary.Key             Object
R Referential.Foreign.Key Column
U Unique.Key              Column
V Check.Option.on.a.view Object
常用:
1、primary key            unique and not null,可以是多个 column 的联合。composite pk 只能被定
义为 table constraint
2、foreign key           parent table 中的 primary key 中的 values 必须包含 child table 中所有的
values. share column 的 parent-child 关系
3、unique
4、check        present in a static list of values permitted for the column.
5、not null 只能被定义在 column constraint。而且是一种内联约束,只能写在列的后面。

Zianed                                     Version 1.1                            2
五种完整性约束:
Check、Unique、Primary Key、Foreign Key 类型可以通过 SELECT * FROM user_constraints
来查询;
NOT NULL 类型可以通过 DESC table_name 来进行查看,在 constraint_type 显示的是 C;
完整性约束是一种规则,不占用任何数据库空间。完整性约束始终存在数据字典中,在执行
SQL 或 PL/SQL 期间使用。
可以指明约束是启用、还是禁用;当约束启用时,增强了数据的完整性;否则,并不检查数
据完整性。




2、constraint的创建和管理
1)增加约束
LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_chk_sal
CHECK(sal>=800);
2)删除约束
LINARY@testjoe.us.oracle.com>ALTER TABLE emp DROP CONSTRAINT emp_chk_sal;

Constraint 的四种状态(Constraint States):
The current status of an integrity constraint can be changed to any of the following 4 options using
the CREATE TABLE or ALTER TABLE statement.
- ENABLE(验证新增数据) ensure that all incoming data conforms to the constraint
- DISABLE(不验证新增数据) allow incoming data, regardless of whether it conforms to the
constraint
- VALIDATE(验证已存在数据) ensure that existing data conforms to the constraint
- NOVALIDATE(不验证已存在数据) existing data does not have to conform to the constraint

In addition:
    ENABLE VALIDATE is the same as ENABLE. The constraint is checked and is guaranteed to
hold for all rows.
    ENABLE NOVALIDATE means that the constraint is checked, but it does not have to be true
for all rows. This allows existing rows to violate the constraint, while ensuring that all new or
modified rows are valid.In an ALTER TABLE statement, ENABLE NOVALIDATE resumes
constraint checking on disabled constraints without first validating all data in the table.
    DISABLE NOVALIDATE is the same as DISABLE. The constraint is not checked and is not
necessarily true.
    DISABLE VALIDATE disables the constraint, drops the index on the constraint, and disallows
any modification of the constrained columns.
    For a UNIQUE constraint, the DISABLE VALIDATE state enables you to load data efficiently
from a nonpartitioned table into a partitioned table using the EXCHANGE PARTITION clause of
the ALTER TABLE statement.



Zianed                                       Version 1.1                                          3
Transitions between these states are governed by the following rules:
     ENABLE implies VALIDATE, unless NOVALIDATE is specified.DISABLE implies
NOVALIDATE, unless VALIDATE is specified.VALIDATE and NOVALIDATE do not have any
default implications for the ENABLE and DISABLE states.
     When a unique or primary key moves from the DISABLE state to the ENABLE state, if there
is no existing index, a unique index is automatically created. Similarly, when a unique or primary
key moves from ENABLE to DISABLE and it is enabled with a unique index, the unique index is
dropped.When any constraint is moved from the NOVALIDATE state to the VALIDATE state, all
data must be checked (this can be very slow). However, moving from VALIDATE to
NOVALIDATE simply forgets that the data was ever checked.Moving a single constraint from the
ENABLE NOVALIDATE state to the ENABLE VALIDATE state does not block reads, writes, or
other DDL statements. It can be done in parallel.




第一种ENABLED、VALIDATED

不检查存在的值,只检查新增加的值。
LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_chk_sal
CHECK(sal>=800);
表已更改。
已用时间: 00: 00: 01.00

LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints');
OWNER                               : LINARY
CONSTRAINT_NAME                          : EMP_CHK_SAL
CONSTRAINT_TYPE                         :C
TABLE_NAME                            : EMP
SEARCH_CONDITION                        : sal>=800
R_OWNER                              :
R_CONSTRAINT_NAME                         :
DELETE_RULE                          :
STATUS                            : ENABLED
DEFERRABLE                            : NOT DEFERRABLE
DEFERRED                            : IMMEDIATE
VALIDATED                           : VALIDATED
GENERATED                            : USER NAME
BAD                               :
RELY                             :
LAST_CHANGE                            : 18-10 月-2009 17:09:04
INDEX_OWNER                            :
INDEX_NAME                            :
INVALID                          :
VIEW_RELATED                          :
-----------------

Zianed                                      Version 1.1                                         4
PL/SQL 过程已成功完成。
已用时间: 00: 00: 00.00




第二种DISABLED、NOT VALIDATED

例如违反约束数据已经存在的增加:
LINARY@testjoe.us.oracle.com>alter table emp add constraint emp_chk_sal check(sal>2000);
alter table emp add constraint emp_chk_sal check(sal>2000)
                                      *
ERROR 位于第 1 行:
ORA-02293: 无法验证 (LINARY.EMP_CHK_SAL) - 违反检查约束条件

例如违反约束数据已经存在的增加:
首先使用 DISABLE 状态进行增加,并不校验数据库中已经存在的数据
LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_chk_sal
CHECK(sal>=2000) DISABLE;
表已更改。
已用时间: 00: 00: 01.00

LINARY@testjoe.us.oracle.com>ALTER TABLE emp ENABLE CONSTRAINT emp_chk_sal;
ALTER TABLE emp ENABLE CONSTRAINT emp_chk_sal
                                   *
ERROR 位于第 1 行:
ORA-02293: 无法验证 (LINARY.EMP_CHK_SAL) - 违反检查约束条件
已用时间: 00: 00: 00.00
LINARY@testjoe.us.oracle.com>

得到状态数据如下:
LINARY@testjoe.us.oracle.com>set serveroutput on;
LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints');
OWNER                               : LINARY
CONSTRAINT_NAME                          : EMP_CHK_SAL
CONSTRAINT_TYPE                        :C
TABLE_NAME                            : EMP
SEARCH_CONDITION                        : sal>=2000
R_OWNER                              :
R_CONSTRAINT_NAME                         :
DELETE_RULE                          :
STATUS                            : DISABLED
DEFERRABLE                            : NOT DEFERRABLE
DEFERRED                            : IMMEDIATE
VALIDATED                           : NOT VALIDATED

Zianed                                    Version 1.1                                      5
GENERATED                                : USER NAME
BAD                                  :
RELY                                 :
LAST_CHANGE                              : 18-10 月-2009 16:53:33
INDEX_OWNER                               :
INDEX_NAME                               :
INVALID                              :
VIEW_RELATED                             :
-----------------
PL/SQL 过程已成功完成。




第三种EBABLED、NOT VALIDATED

不检查存在的值,只检查新增加的值。
LINARY@testjoe.us.oracle.com>ALTER TABLE emp DROP CONSTRAINT emp_chk_sal;
表已更改。
已用时间: 00: 00: 00.00

LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_chk_sal
check(sal>=2000) ENABLE NOVALIDATE;
表已更改。
已用时间: 00: 00: 00.00

LINARY@testjoe.us.oracle.com>insert into emp(empno,ename,sal) values(1001,'zianed',1600);
insert into emp(empno,ename,sal) values(1001,'zianed',1600)
*
ERROR 位于第 1 行:
ORA-02290: 违反检查约束条件 (LINARY.EMP_CHK_SAL)
已用时间: 00: 00: 00.00

LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints');
OWNER                               : LINARY
CONSTRAINT_NAME                          : EMP_CHK_SAL
CONSTRAINT_TYPE                        :C
TABLE_NAME                            : EMP
SEARCH_CONDITION                        : sal>=800
R_OWNER                              :
R_CONSTRAINT_NAME                         :
DELETE_RULE                          :
STATUS                            : ENABLED
DEFERRABLE                           : NOT DEFERRABLE
DEFERRED                            : IMMEDIATE

Zianed                                       Version 1.1                                    6
VALIDATED                                : NOT VALIDATED
GENERATED                                 : USER NAME
BAD                                  :
RELY                                 :
LAST_CHANGE                              : 18-10 月-2009 17:29:20
INDEX_OWNER                               :
INDEX_NAME                               :
INVALID                              :
VIEW_RELATED                             :
-----------------
PL/SQL 过程已成功完成。
已用时间: 00: 00: 00.00
LINARY@testjoe.us.oracle.com>




第四种DISABLED、VALIDATED

不验证内部数据,验证新插入数据
LINARY@testjoe.us.oracle.com>ALTER TABLE emp DROP CONSTRAINT emp_chk_sal;
表已更改。

LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_chk_sal
check(sal>=2000) DISABLE VALIDATE;
ALTER TABLE emp ADD CONSTRAINT emp_chk_sal check(sal>=2000) DISABLE
VALIDATE
                                *
ERROR 位于第 1 行:
ORA-02293: 无法验证 (LINARY.EMP_CHK_SAL) - 违反检查约束条件

LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints');
PL/SQL 过程已成功完成。

LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_chk_sal
check(sal>=800) DISABLE VALIDATE;
表已更改。

LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints');
OWNER                              : LINARY
CONSTRAINT_NAME                         : EMP_CHK_SAL
CONSTRAINT_TYPE                       :C
TABLE_NAME                           : EMP
SEARCH_CONDITION                       : sal>=800
R_OWNER                             :

Zianed                                       Version 1.1                           7
R_CONSTRAINT_NAME                       :
DELETE_RULE                           :
STATUS                             : DISABLED
DEFERRABLE                             : NOT DEFERRABLE
DEFERRED                             : IMMEDIATE
VALIDATED                            : VALIDATED
GENERATED                             : USER NAME
BAD                                :
RELY                               :
LAST_CHANGE                             : 18-10 月-2009 17:34:14
INDEX_OWNER                             :
INDEX_NAME                             :
INVALID                            :
VIEW_RELATED                           :
-----------------
PL/SQL 过程已成功完成。

LINARY@testjoe.us.oracle.com>insert into emp(empno,ename,sal) values(1001,'zianed',600);
insert into emp(empno,ename,sal) values(1001,'zianed',600)
*
ERROR 位于第 1 行:
ORA-25128: 不能对带有禁用和验证约束条件 (LINARY.EMP_CHK_SAL)
的表进行插入/更新/删除

LINARY@testjoe.us.oracle.com>




3、constraint的种类

3.1、CHECK约束

CONSTRAINT [constraint_name] CHECK (condition);

添加:
ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK(sal>=2000);
ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK(sex in ('F','M');
删除:
ALTER TABLE table_name DROP CONSTRAINT constraint_name;

Check 约束不保护 LOB 数据类型的数据列和对象、嵌套表、VARRY、ref 等。一个列可以有
多个 Check 约束,一个 Check 约束也可以保护多个列。

Zianed                                      Version 1.1                                    8
3.2、NOT NULL约束

一种特殊的 check 约束,保持数据列不为空值。
NOT NULL 约束作用在单一列上,并保持该列不为空;默认 ORACLE 允许任何列都可以有
NULL 值。

添加:
ALTER TABLE table_name MODIFY column_name NOT NULL;
删除:
ALTER TABLE table_name MODIFY column_name NULL;

LINARY@testjoe.us.oracle.com>alter table emp modify sal not null;
表已更改。
LINARY@testjoe.us.oracle.com>desc emp
 名称                                                              是否为空? 类型
 ----------------------------------------- -------- ----------------------------
 EMPNO                                                                           NUMBER(4)
 ENAME                                                                           VARCHAR2(10)
 JOB                                                                           VARCHAR2(9)
 MGR                                                                             NUMBER(4)
 HIREDATE                                                                        DATE
 SAL                                                              NOT NULL NUMBER(7,2)
 COMM                                                                             NUMBER(7,2)
 DEPTNO                                                                          NUMBER(2)
LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints');
OWNER                                            : LINARY
CONSTRAINT_NAME                                       : EMP_CHK_SAL
CONSTRAINT_TYPE                                      :C
TABLE_NAME                                         : EMP
SEARCH_CONDITION                                     : sal>=800
R_OWNER                                           :
R_CONSTRAINT_NAME                                      :
DELETE_RULE                                       :
STATUS                                         : DISABLED
DEFERRABLE                                         : NOT DEFERRABLE
DEFERRED                                         : IMMEDIATE
VALIDATED                                        : VALIDATED
GENERATED                                         : USER NAME
BAD                                            :
RELY                                          :
LAST_CHANGE                                         : 18-10 月-2009 17:34:14
INDEX_OWNER                                         :

Zianed                                          Version 1.1                                     9
INDEX_NAME                          :
INVALID                         :
VIEW_RELATED                        :
-----------------
OWNER                             : LINARY
CONSTRAINT_NAME                        : SYS_C003039
CONSTRAINT_TYPE                       :C
TABLE_NAME                          : EMP
SEARCH_CONDITION                      : "SAL" IS NOT NULL
R_OWNER                            :
R_CONSTRAINT_NAME                       :
DELETE_RULE                        :
STATUS                          : ENABLED
DEFERRABLE                          : NOT DEFERRABLE
DEFERRED                          : IMMEDIATE
VALIDATED                         : VALIDATED
GENERATED                          : GENERATED NAME
BAD                             :
RELY                            :
LAST_CHANGE                          : 18-10 月-2009 20:24:06
INDEX_OWNER                          :
INDEX_NAME                          :
INVALID                         :
VIEW_RELATED                        :
-----------------
PL/SQL 过程已成功完成。
LINARY@testjoe.us.oracle.com>




3.3、Unique约束

唯一性约束可以保证数据库中一个列或者多个列不具有相同的值。

添加:
column_name data_type CONSTRAINT constraint_name UNIQUE
ALTER TABLE table_name ADD CONSTRAINT constraint_name (column_1[,column_n])
UNIQUE USING INDEX TABLESPACE (tablespace_name) STORAGE (stored clause);
UNIQUE (column1,column2) USING INDEX TABLESPACE users STORAGE (INITIAL 1M
NEXT 10M PCTINCREASE 0)
默认创建与 constraint_name 同名的 UNIQUE 索引
删除:
ALTER TABLE table_name DROP CONSTRAINT emp_uiq_ename;

删除或禁用唯一性约束会同时删除相关联的唯一索引导致降低了数据库性能。因而进行如下

Zianed                                  Version 1.1                      10
操作:在唯一性约束保护的列上创建非唯一性索引,然后添加唯一性约束



LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_uiq_ename
UNiQUE(ename);
表已更改。

LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints');
OWNER                               : LINARY
CONSTRAINT_NAME                           : EMP_UIQ_ENAME
CONSTRAINT_TYPE                         :U
TABLE_NAME                            : EMP
SEARCH_CONDITION                        :
R_OWNER                              :
R_CONSTRAINT_NAME                          :
DELETE_RULE                          :
STATUS                            : ENABLED
DEFERRABLE                            : NOT DEFERRABLE
DEFERRED                            : IMMEDIATE
VALIDATED                           : VALIDATED
GENERATED                            : USER NAME
BAD                               :
RELY                             :
LAST_CHANGE                            : 18-10 月-2009 20:59:50
INDEX_OWNER                            : LINARY
INDEX_NAME                            : EMP_UIQ_ENAME
INVALID                          :
VIEW_RELATED                          :
-----------------
PL/SQL 过程已成功完成。



LINARY@testjoe.us.oracle.com>exec print_table('select * from user_indexes');
INDEX_NAME                           : EMP_UIQ_ENAME
INDEX_TYPE                         : NORMAL
TABLE_OWNER                            : LINARY
TABLE_NAME                           : EMP
TABLE_TYPE                         : TABLE
UNIQUENESS                          : UNIQUE
COMPRESSION                          : DISABLED
PREFIX_LENGTH                        :
TABLESPACE_NAME                         : SYSTEM
INI_TRANS                         :2
MAX_TRANS                             : 255


Zianed                                    Version 1.1                              11
INITIAL_EXTENT                    : 65536
NEXT_EXTENT                           :
MIN_EXTENTS                          :1
MAX_EXTENTS                            : 2147483645
PCT_INCREASE                       :
PCT_THRESHOLD                          :
INCLUDE_COLUMN                            :
FREELISTS                       :1
FREELIST_GROUPS                      :1
PCT_FREE                         : 10
LOGGING                           : YES
BLEVEL                           :
LEAF_BLOCKS                          :
DISTINCT_KEYS                      :
AVG_LEAF_BLOCKS_PER_KEY                     :
AVG_DATA_BLOCKS_PER_KEY                     :
CLUSTERING_FACTOR                        :
STATUS                          : VALID
NUM_ROWS                               :
SAMPLE_SIZE                       :
LAST_ANALYZED                           :
DEGREE                            :1
INSTANCES                         :1
PARTITIONED                       : NO
TEMPORARY                             :N
GENERATED                           :N
SECONDARY                            :N
BUFFER_POOL                         : DEFAULT
USER_STATS                        : NO
DURATION                           :
PCT_DIRECT_ACCESS                      :
ITYP_OWNER                           :
ITYP_NAME                          :
PARAMETERS                           :
GLOBAL_STATS                         : NO
DOMIDX_STATUS                          :
DOMIDX_OPSTATUS                         :
FUNCIDX_STATUS                        :
JOIN_INDEX                       : NO
-----------------

PL/SQL 过程已成功完成。

LINARY@testjoe.us.oracle.com>


Zianed                                Version 1.1     12
LINARY@testjoe.us.oracle.com>ALTER TABLE emp DROP CONSTRAINT emp_uiq_ename;

表已更改。

LINARY@testjoe.us.oracle.com>exec print_table('select * from user_indexes');

PL/SQL 过程已成功完成。

LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints');
OWNER                               : LINARY
CONSTRAINT_NAME                          : EMP_CHK_SAL
CONSTRAINT_TYPE                         :C
TABLE_NAME                            : EMP
SEARCH_CONDITION                        : sal>=800
R_OWNER                              :
R_CONSTRAINT_NAME                         :
DELETE_RULE                          :
STATUS                            : DISABLED
DEFERRABLE                            : NOT DEFERRABLE
DEFERRED                            : IMMEDIATE
VALIDATED                           : VALIDATED
GENERATED                            : USER NAME
BAD                               :
RELY                             :
LAST_CHANGE                            : 18-10 月-2009 17:34:14
INDEX_OWNER                            :
INDEX_NAME                            :
INVALID                          :
VIEW_RELATED                          :
-----------------

PL/SQL 过程已成功完成。




3.4、Primary Key约束

唯一非空约束,可以存在一个或者多个列上。

添加:
ALTER    TABLE     table_name ADD   CONSTRAINT                  constraint_name    PRIMARY
KEY(column_1[,column_n]);
删除或者禁用:
ALTER TABLE table_name DROP PRIMARY KEY;

Zianed                                    Version 1.1                                   13
ALTER TABLE table_name DISABLE PRIMARY KEY;



LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_pk_empno
PRIMARY KEY(empno);

表已更改。

LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints');
OWNER                               : LINARY
CONSTRAINT_NAME                           : EMP_PK_EMPNO
CONSTRAINT_TYPE                         :P
TABLE_NAME                            : EMP
SEARCH_CONDITION                        :
R_OWNER                              :
R_CONSTRAINT_NAME                          :
DELETE_RULE                          :
STATUS                            : ENABLED
DEFERRABLE                            : NOT DEFERRABLE
DEFERRED                            : IMMEDIATE
VALIDATED                           : VALIDATED
GENERATED                            : USER NAME
BAD                               :
RELY                             :
LAST_CHANGE                            : 18-10 月-2009 21:13:01
INDEX_OWNER                            : LINARY
INDEX_NAME                            : EMP_PK_EMPNO
INVALID                          :
VIEW_RELATED                          :
-----------------

PL/SQL 过程已成功完成。

LINARY@testjoe.us.oracle.com>exec print_table('select * from user_indexes');
INDEX_NAME                           : EMP_PK_EMPNO
INDEX_TYPE                         : NORMAL
TABLE_OWNER                            : LINARY
TABLE_NAME                           : EMP
TABLE_TYPE                         : TABLE
UNIQUENESS                          : UNIQUE
COMPRESSION                          : DISABLED
PREFIX_LENGTH                        :
TABLESPACE_NAME                         : SYSTEM
INI_TRANS                         :2


Zianed                                    Version 1.1                              14
MAX_TRANS                       : 255
INITIAL_EXTENT              : 65536
NEXT_EXTENT                     :
MIN_EXTENTS                    :1
MAX_EXTENTS                      : 2147483645
PCT_INCREASE                 :
PCT_THRESHOLD                    :
INCLUDE_COLUMN                      :
FREELISTS                 :1
FREELIST_GROUPS                :1
PCT_FREE                   : 10
LOGGING                     : YES
BLEVEL                     :
LEAF_BLOCKS                    :
DISTINCT_KEYS                :
AVG_LEAF_BLOCKS_PER_KEY               :
AVG_DATA_BLOCKS_PER_KEY               :
CLUSTERING_FACTOR                  :
STATUS                    : VALID
NUM_ROWS                         :
SAMPLE_SIZE                 :
LAST_ANALYZED                     :
DEGREE                      :1
INSTANCES                   :1
PARTITIONED                 : NO
TEMPORARY                       :N
GENERATED                     :N
SECONDARY                      :N
BUFFER_POOL                   : DEFAULT
USER_STATS                  : NO
DURATION                     :
PCT_DIRECT_ACCESS                :
ITYP_OWNER                     :
ITYP_NAME                    :
PARAMETERS                     :
GLOBAL_STATS                   : NO
DOMIDX_STATUS                    :
DOMIDX_OPSTATUS                   :
FUNCIDX_STATUS                  :
JOIN_INDEX                 : NO
-----------------

PL/SQL 过程已成功完成。



Zianed                          Version 1.1     15
LINARY@testjoe.us.oracle.com>
LINARY@testjoe.us.oracle.com>ALTER TABLE emp DROP PRIMARY KEY;

表已更改。

LINARY@testjoe.us.oracle.com>




3.5、Foreign Key约束

子表的对应的列上的值,要么为父表上对应的值,要么为空。
外部键约束保护的数据列中 NULL 值的处理可能产生不可预料的结果。ORACLE 使用 ISO
standar Match None 规则增强外部键约束,这个规则规定如果任何外部键作用的数据列包含
有一个 NULL 值,那么任何保留该键的数据列在父表中没有匹配值。

ON DELETE 子句标识 ORACLE 父记录(parent record)被删后,子记录的行为。默认情况下
禁止在子记录存在值时删除父记录。

LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_fk_deptno
FOREIGN KEY(deptno) REFERENCES dept(deptno) ON DELETE SET NULL;
ALTER TABLE emp ADD CONSTRAINT emp_fk_deptno FOREIGN KEY(deptno)
REFERENCES dept(deptno) ON DELETE SET NULL

*
ERROR 位于第 1 行:
ORA-02270: 此列列表的唯一或主键不匹配



LINARY@testjoe.us.oracle.com>select * from dept;

      DEPTNO DNAME                         LOC
---------- -------------- -------------
            10 ACCOUNTING                 NEW YORK
            20 RESEARCH                  DALLAS
            30 SALES                    CHICAGO
            40 OPERATIONS                BOSTON

LINARY@testjoe.us.oracle.com>ALTER TABLE dept ADD CONSTRAINT dept_uiq_deptno
UNiQUE(deptno);
表已更改。

LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_fk_deptno
FOREIGN KEY(deptno) REFERENCES dept(deptno) ON DELETE SET NULL;

Zianed                                       Version 1.1                  16
表已更改。

LINARY@testjoe.us.oracle.com>




4、延迟约束检查
延迟约束检验(Deferred Constraint Checking)
    约束检验分两种情况,一种是立即约束检验(immediately checking)           ,在每一条语句结
束 后 立 即 检 验 数 据 是 否 满 足 约 束 条 件 ; 另 一 种 是 延 迟 约 束 检 验 ( Deferred Constraint
Checking),在事务处理完成之后对数据进行检验。默认时是 Oracle 约束检验是立即检验
(immediately checking),如果不满足约束将立即得到一条错误信息,但用户可以通过 SET
CONSTRAINT 语句选择延迟约束检验。语法如下:
SET CONSTRAINT constraint_name|ALL DEFERRED|IMMEDIATE ;

LINARY@testjoe.us.oracle.com>SET CONSTRAINT ALL DEFERRED;
约束条件已设置。
LINARY@testjoe.us.oracle.com>SET CONSTRAINT ALL IMMEDIATE;
约束条件已设置。
LINARY@testjoe.us.oracle.com>



Reference:
Data Integrity
http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/data_int.htm#i6686
CREATE TABLE
http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_7002.htm#i209533
ALTER TABLE
http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_3001.htm#CJAHH
IBI
http://tahiti.oracle.com/
http://www.databasedesign-resource.com/enabling-and-disabling-oracle-constraints.html
http://ss64.com/ora/syntax-constraints.html




Zianed                                  Version 1.1                                     17
Zianed
Homepage:http://my.unix-center.net/~Zianed/
Mail:zianed@live.cn
QQ:1196123432
Date:2009-10-18




Zianed                        Version 1.1     18

Mais conteúdo relacionado

Destaque

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destaque (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Oracle的Constraint约束V1.1

  • 1. Oracle 的 Constraint 约束 Zianed Hou zianed@live.cn 1、constraint类型介绍 2、constraint的创建和管理 第一种ENABLED、VALIDATED 第二种DISABLED、NOT VALIDATED 第三种EBABLED、NOT VALIDATED 第四种DISABLED、VALIDATED 3、constraint的种类 3.1、CHECK约束 3.2、NOT NULL约束 3.3、Unique约束 3.4、Primary Key约束 3.5、Foreign Key约束 4、延迟约束检查 Zianed Version 1.1 1
  • 2. 1、constraint类型介绍 SQL> select distinct constraint_type from dba_constraints; CONSTRAINT_TYPE - V R U P ? C O 已选择 7 行。 SQL> 类型说明: V——(Check Option on a view) R——(Reference Froeign Key 参照外键约束 U——(Unique)唯一性约束 P——(Primary Key)unique and not null,主键约束 ?—— C——(Check)present in a static list of values permitted for the column,检查约束 O——(Read Only on a view) 描述: Type.Code Type .Description Acts.On.Level C Check.on.a.table Column O Read.Only.on.a.view Object P Primary.Key Object R Referential.Foreign.Key Column U Unique.Key Column V Check.Option.on.a.view Object 常用: 1、primary key unique and not null,可以是多个 column 的联合。composite pk 只能被定 义为 table constraint 2、foreign key parent table 中的 primary key 中的 values 必须包含 child table 中所有的 values. share column 的 parent-child 关系 3、unique 4、check present in a static list of values permitted for the column. 5、not null 只能被定义在 column constraint。而且是一种内联约束,只能写在列的后面。 Zianed Version 1.1 2
  • 3. 五种完整性约束: Check、Unique、Primary Key、Foreign Key 类型可以通过 SELECT * FROM user_constraints 来查询; NOT NULL 类型可以通过 DESC table_name 来进行查看,在 constraint_type 显示的是 C; 完整性约束是一种规则,不占用任何数据库空间。完整性约束始终存在数据字典中,在执行 SQL 或 PL/SQL 期间使用。 可以指明约束是启用、还是禁用;当约束启用时,增强了数据的完整性;否则,并不检查数 据完整性。 2、constraint的创建和管理 1)增加约束 LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_chk_sal CHECK(sal>=800); 2)删除约束 LINARY@testjoe.us.oracle.com>ALTER TABLE emp DROP CONSTRAINT emp_chk_sal; Constraint 的四种状态(Constraint States): The current status of an integrity constraint can be changed to any of the following 4 options using the CREATE TABLE or ALTER TABLE statement. - ENABLE(验证新增数据) ensure that all incoming data conforms to the constraint - DISABLE(不验证新增数据) allow incoming data, regardless of whether it conforms to the constraint - VALIDATE(验证已存在数据) ensure that existing data conforms to the constraint - NOVALIDATE(不验证已存在数据) existing data does not have to conform to the constraint In addition: ENABLE VALIDATE is the same as ENABLE. The constraint is checked and is guaranteed to hold for all rows. ENABLE NOVALIDATE means that the constraint is checked, but it does not have to be true for all rows. This allows existing rows to violate the constraint, while ensuring that all new or modified rows are valid.In an ALTER TABLE statement, ENABLE NOVALIDATE resumes constraint checking on disabled constraints without first validating all data in the table. DISABLE NOVALIDATE is the same as DISABLE. The constraint is not checked and is not necessarily true. DISABLE VALIDATE disables the constraint, drops the index on the constraint, and disallows any modification of the constrained columns. For a UNIQUE constraint, the DISABLE VALIDATE state enables you to load data efficiently from a nonpartitioned table into a partitioned table using the EXCHANGE PARTITION clause of the ALTER TABLE statement. Zianed Version 1.1 3
  • 4. Transitions between these states are governed by the following rules: ENABLE implies VALIDATE, unless NOVALIDATE is specified.DISABLE implies NOVALIDATE, unless VALIDATE is specified.VALIDATE and NOVALIDATE do not have any default implications for the ENABLE and DISABLE states. When a unique or primary key moves from the DISABLE state to the ENABLE state, if there is no existing index, a unique index is automatically created. Similarly, when a unique or primary key moves from ENABLE to DISABLE and it is enabled with a unique index, the unique index is dropped.When any constraint is moved from the NOVALIDATE state to the VALIDATE state, all data must be checked (this can be very slow). However, moving from VALIDATE to NOVALIDATE simply forgets that the data was ever checked.Moving a single constraint from the ENABLE NOVALIDATE state to the ENABLE VALIDATE state does not block reads, writes, or other DDL statements. It can be done in parallel. 第一种ENABLED、VALIDATED 不检查存在的值,只检查新增加的值。 LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_chk_sal CHECK(sal>=800); 表已更改。 已用时间: 00: 00: 01.00 LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints'); OWNER : LINARY CONSTRAINT_NAME : EMP_CHK_SAL CONSTRAINT_TYPE :C TABLE_NAME : EMP SEARCH_CONDITION : sal>=800 R_OWNER : R_CONSTRAINT_NAME : DELETE_RULE : STATUS : ENABLED DEFERRABLE : NOT DEFERRABLE DEFERRED : IMMEDIATE VALIDATED : VALIDATED GENERATED : USER NAME BAD : RELY : LAST_CHANGE : 18-10 月-2009 17:09:04 INDEX_OWNER : INDEX_NAME : INVALID : VIEW_RELATED : ----------------- Zianed Version 1.1 4
  • 5. PL/SQL 过程已成功完成。 已用时间: 00: 00: 00.00 第二种DISABLED、NOT VALIDATED 例如违反约束数据已经存在的增加: LINARY@testjoe.us.oracle.com>alter table emp add constraint emp_chk_sal check(sal>2000); alter table emp add constraint emp_chk_sal check(sal>2000) * ERROR 位于第 1 行: ORA-02293: 无法验证 (LINARY.EMP_CHK_SAL) - 违反检查约束条件 例如违反约束数据已经存在的增加: 首先使用 DISABLE 状态进行增加,并不校验数据库中已经存在的数据 LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_chk_sal CHECK(sal>=2000) DISABLE; 表已更改。 已用时间: 00: 00: 01.00 LINARY@testjoe.us.oracle.com>ALTER TABLE emp ENABLE CONSTRAINT emp_chk_sal; ALTER TABLE emp ENABLE CONSTRAINT emp_chk_sal * ERROR 位于第 1 行: ORA-02293: 无法验证 (LINARY.EMP_CHK_SAL) - 违反检查约束条件 已用时间: 00: 00: 00.00 LINARY@testjoe.us.oracle.com> 得到状态数据如下: LINARY@testjoe.us.oracle.com>set serveroutput on; LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints'); OWNER : LINARY CONSTRAINT_NAME : EMP_CHK_SAL CONSTRAINT_TYPE :C TABLE_NAME : EMP SEARCH_CONDITION : sal>=2000 R_OWNER : R_CONSTRAINT_NAME : DELETE_RULE : STATUS : DISABLED DEFERRABLE : NOT DEFERRABLE DEFERRED : IMMEDIATE VALIDATED : NOT VALIDATED Zianed Version 1.1 5
  • 6. GENERATED : USER NAME BAD : RELY : LAST_CHANGE : 18-10 月-2009 16:53:33 INDEX_OWNER : INDEX_NAME : INVALID : VIEW_RELATED : ----------------- PL/SQL 过程已成功完成。 第三种EBABLED、NOT VALIDATED 不检查存在的值,只检查新增加的值。 LINARY@testjoe.us.oracle.com>ALTER TABLE emp DROP CONSTRAINT emp_chk_sal; 表已更改。 已用时间: 00: 00: 00.00 LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_chk_sal check(sal>=2000) ENABLE NOVALIDATE; 表已更改。 已用时间: 00: 00: 00.00 LINARY@testjoe.us.oracle.com>insert into emp(empno,ename,sal) values(1001,'zianed',1600); insert into emp(empno,ename,sal) values(1001,'zianed',1600) * ERROR 位于第 1 行: ORA-02290: 违反检查约束条件 (LINARY.EMP_CHK_SAL) 已用时间: 00: 00: 00.00 LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints'); OWNER : LINARY CONSTRAINT_NAME : EMP_CHK_SAL CONSTRAINT_TYPE :C TABLE_NAME : EMP SEARCH_CONDITION : sal>=800 R_OWNER : R_CONSTRAINT_NAME : DELETE_RULE : STATUS : ENABLED DEFERRABLE : NOT DEFERRABLE DEFERRED : IMMEDIATE Zianed Version 1.1 6
  • 7. VALIDATED : NOT VALIDATED GENERATED : USER NAME BAD : RELY : LAST_CHANGE : 18-10 月-2009 17:29:20 INDEX_OWNER : INDEX_NAME : INVALID : VIEW_RELATED : ----------------- PL/SQL 过程已成功完成。 已用时间: 00: 00: 00.00 LINARY@testjoe.us.oracle.com> 第四种DISABLED、VALIDATED 不验证内部数据,验证新插入数据 LINARY@testjoe.us.oracle.com>ALTER TABLE emp DROP CONSTRAINT emp_chk_sal; 表已更改。 LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_chk_sal check(sal>=2000) DISABLE VALIDATE; ALTER TABLE emp ADD CONSTRAINT emp_chk_sal check(sal>=2000) DISABLE VALIDATE * ERROR 位于第 1 行: ORA-02293: 无法验证 (LINARY.EMP_CHK_SAL) - 违反检查约束条件 LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints'); PL/SQL 过程已成功完成。 LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_chk_sal check(sal>=800) DISABLE VALIDATE; 表已更改。 LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints'); OWNER : LINARY CONSTRAINT_NAME : EMP_CHK_SAL CONSTRAINT_TYPE :C TABLE_NAME : EMP SEARCH_CONDITION : sal>=800 R_OWNER : Zianed Version 1.1 7
  • 8. R_CONSTRAINT_NAME : DELETE_RULE : STATUS : DISABLED DEFERRABLE : NOT DEFERRABLE DEFERRED : IMMEDIATE VALIDATED : VALIDATED GENERATED : USER NAME BAD : RELY : LAST_CHANGE : 18-10 月-2009 17:34:14 INDEX_OWNER : INDEX_NAME : INVALID : VIEW_RELATED : ----------------- PL/SQL 过程已成功完成。 LINARY@testjoe.us.oracle.com>insert into emp(empno,ename,sal) values(1001,'zianed',600); insert into emp(empno,ename,sal) values(1001,'zianed',600) * ERROR 位于第 1 行: ORA-25128: 不能对带有禁用和验证约束条件 (LINARY.EMP_CHK_SAL) 的表进行插入/更新/删除 LINARY@testjoe.us.oracle.com> 3、constraint的种类 3.1、CHECK约束 CONSTRAINT [constraint_name] CHECK (condition); 添加: ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK(sal>=2000); ALTER TABLE table_name ADD CONSTRAINT constraint_name CHECK(sex in ('F','M'); 删除: ALTER TABLE table_name DROP CONSTRAINT constraint_name; Check 约束不保护 LOB 数据类型的数据列和对象、嵌套表、VARRY、ref 等。一个列可以有 多个 Check 约束,一个 Check 约束也可以保护多个列。 Zianed Version 1.1 8
  • 9. 3.2、NOT NULL约束 一种特殊的 check 约束,保持数据列不为空值。 NOT NULL 约束作用在单一列上,并保持该列不为空;默认 ORACLE 允许任何列都可以有 NULL 值。 添加: ALTER TABLE table_name MODIFY column_name NOT NULL; 删除: ALTER TABLE table_name MODIFY column_name NULL; LINARY@testjoe.us.oracle.com>alter table emp modify sal not null; 表已更改。 LINARY@testjoe.us.oracle.com>desc emp 名称 是否为空? 类型 ----------------------------------------- -------- ---------------------------- EMPNO NUMBER(4) ENAME VARCHAR2(10) JOB VARCHAR2(9) MGR NUMBER(4) HIREDATE DATE SAL NOT NULL NUMBER(7,2) COMM NUMBER(7,2) DEPTNO NUMBER(2) LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints'); OWNER : LINARY CONSTRAINT_NAME : EMP_CHK_SAL CONSTRAINT_TYPE :C TABLE_NAME : EMP SEARCH_CONDITION : sal>=800 R_OWNER : R_CONSTRAINT_NAME : DELETE_RULE : STATUS : DISABLED DEFERRABLE : NOT DEFERRABLE DEFERRED : IMMEDIATE VALIDATED : VALIDATED GENERATED : USER NAME BAD : RELY : LAST_CHANGE : 18-10 月-2009 17:34:14 INDEX_OWNER : Zianed Version 1.1 9
  • 10. INDEX_NAME : INVALID : VIEW_RELATED : ----------------- OWNER : LINARY CONSTRAINT_NAME : SYS_C003039 CONSTRAINT_TYPE :C TABLE_NAME : EMP SEARCH_CONDITION : "SAL" IS NOT NULL R_OWNER : R_CONSTRAINT_NAME : DELETE_RULE : STATUS : ENABLED DEFERRABLE : NOT DEFERRABLE DEFERRED : IMMEDIATE VALIDATED : VALIDATED GENERATED : GENERATED NAME BAD : RELY : LAST_CHANGE : 18-10 月-2009 20:24:06 INDEX_OWNER : INDEX_NAME : INVALID : VIEW_RELATED : ----------------- PL/SQL 过程已成功完成。 LINARY@testjoe.us.oracle.com> 3.3、Unique约束 唯一性约束可以保证数据库中一个列或者多个列不具有相同的值。 添加: column_name data_type CONSTRAINT constraint_name UNIQUE ALTER TABLE table_name ADD CONSTRAINT constraint_name (column_1[,column_n]) UNIQUE USING INDEX TABLESPACE (tablespace_name) STORAGE (stored clause); UNIQUE (column1,column2) USING INDEX TABLESPACE users STORAGE (INITIAL 1M NEXT 10M PCTINCREASE 0) 默认创建与 constraint_name 同名的 UNIQUE 索引 删除: ALTER TABLE table_name DROP CONSTRAINT emp_uiq_ename; 删除或禁用唯一性约束会同时删除相关联的唯一索引导致降低了数据库性能。因而进行如下 Zianed Version 1.1 10
  • 11. 操作:在唯一性约束保护的列上创建非唯一性索引,然后添加唯一性约束 LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_uiq_ename UNiQUE(ename); 表已更改。 LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints'); OWNER : LINARY CONSTRAINT_NAME : EMP_UIQ_ENAME CONSTRAINT_TYPE :U TABLE_NAME : EMP SEARCH_CONDITION : R_OWNER : R_CONSTRAINT_NAME : DELETE_RULE : STATUS : ENABLED DEFERRABLE : NOT DEFERRABLE DEFERRED : IMMEDIATE VALIDATED : VALIDATED GENERATED : USER NAME BAD : RELY : LAST_CHANGE : 18-10 月-2009 20:59:50 INDEX_OWNER : LINARY INDEX_NAME : EMP_UIQ_ENAME INVALID : VIEW_RELATED : ----------------- PL/SQL 过程已成功完成。 LINARY@testjoe.us.oracle.com>exec print_table('select * from user_indexes'); INDEX_NAME : EMP_UIQ_ENAME INDEX_TYPE : NORMAL TABLE_OWNER : LINARY TABLE_NAME : EMP TABLE_TYPE : TABLE UNIQUENESS : UNIQUE COMPRESSION : DISABLED PREFIX_LENGTH : TABLESPACE_NAME : SYSTEM INI_TRANS :2 MAX_TRANS : 255 Zianed Version 1.1 11
  • 12. INITIAL_EXTENT : 65536 NEXT_EXTENT : MIN_EXTENTS :1 MAX_EXTENTS : 2147483645 PCT_INCREASE : PCT_THRESHOLD : INCLUDE_COLUMN : FREELISTS :1 FREELIST_GROUPS :1 PCT_FREE : 10 LOGGING : YES BLEVEL : LEAF_BLOCKS : DISTINCT_KEYS : AVG_LEAF_BLOCKS_PER_KEY : AVG_DATA_BLOCKS_PER_KEY : CLUSTERING_FACTOR : STATUS : VALID NUM_ROWS : SAMPLE_SIZE : LAST_ANALYZED : DEGREE :1 INSTANCES :1 PARTITIONED : NO TEMPORARY :N GENERATED :N SECONDARY :N BUFFER_POOL : DEFAULT USER_STATS : NO DURATION : PCT_DIRECT_ACCESS : ITYP_OWNER : ITYP_NAME : PARAMETERS : GLOBAL_STATS : NO DOMIDX_STATUS : DOMIDX_OPSTATUS : FUNCIDX_STATUS : JOIN_INDEX : NO ----------------- PL/SQL 过程已成功完成。 LINARY@testjoe.us.oracle.com> Zianed Version 1.1 12
  • 13. LINARY@testjoe.us.oracle.com>ALTER TABLE emp DROP CONSTRAINT emp_uiq_ename; 表已更改。 LINARY@testjoe.us.oracle.com>exec print_table('select * from user_indexes'); PL/SQL 过程已成功完成。 LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints'); OWNER : LINARY CONSTRAINT_NAME : EMP_CHK_SAL CONSTRAINT_TYPE :C TABLE_NAME : EMP SEARCH_CONDITION : sal>=800 R_OWNER : R_CONSTRAINT_NAME : DELETE_RULE : STATUS : DISABLED DEFERRABLE : NOT DEFERRABLE DEFERRED : IMMEDIATE VALIDATED : VALIDATED GENERATED : USER NAME BAD : RELY : LAST_CHANGE : 18-10 月-2009 17:34:14 INDEX_OWNER : INDEX_NAME : INVALID : VIEW_RELATED : ----------------- PL/SQL 过程已成功完成。 3.4、Primary Key约束 唯一非空约束,可以存在一个或者多个列上。 添加: ALTER TABLE table_name ADD CONSTRAINT constraint_name PRIMARY KEY(column_1[,column_n]); 删除或者禁用: ALTER TABLE table_name DROP PRIMARY KEY; Zianed Version 1.1 13
  • 14. ALTER TABLE table_name DISABLE PRIMARY KEY; LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_pk_empno PRIMARY KEY(empno); 表已更改。 LINARY@testjoe.us.oracle.com>exec print_table('select * from user_constraints'); OWNER : LINARY CONSTRAINT_NAME : EMP_PK_EMPNO CONSTRAINT_TYPE :P TABLE_NAME : EMP SEARCH_CONDITION : R_OWNER : R_CONSTRAINT_NAME : DELETE_RULE : STATUS : ENABLED DEFERRABLE : NOT DEFERRABLE DEFERRED : IMMEDIATE VALIDATED : VALIDATED GENERATED : USER NAME BAD : RELY : LAST_CHANGE : 18-10 月-2009 21:13:01 INDEX_OWNER : LINARY INDEX_NAME : EMP_PK_EMPNO INVALID : VIEW_RELATED : ----------------- PL/SQL 过程已成功完成。 LINARY@testjoe.us.oracle.com>exec print_table('select * from user_indexes'); INDEX_NAME : EMP_PK_EMPNO INDEX_TYPE : NORMAL TABLE_OWNER : LINARY TABLE_NAME : EMP TABLE_TYPE : TABLE UNIQUENESS : UNIQUE COMPRESSION : DISABLED PREFIX_LENGTH : TABLESPACE_NAME : SYSTEM INI_TRANS :2 Zianed Version 1.1 14
  • 15. MAX_TRANS : 255 INITIAL_EXTENT : 65536 NEXT_EXTENT : MIN_EXTENTS :1 MAX_EXTENTS : 2147483645 PCT_INCREASE : PCT_THRESHOLD : INCLUDE_COLUMN : FREELISTS :1 FREELIST_GROUPS :1 PCT_FREE : 10 LOGGING : YES BLEVEL : LEAF_BLOCKS : DISTINCT_KEYS : AVG_LEAF_BLOCKS_PER_KEY : AVG_DATA_BLOCKS_PER_KEY : CLUSTERING_FACTOR : STATUS : VALID NUM_ROWS : SAMPLE_SIZE : LAST_ANALYZED : DEGREE :1 INSTANCES :1 PARTITIONED : NO TEMPORARY :N GENERATED :N SECONDARY :N BUFFER_POOL : DEFAULT USER_STATS : NO DURATION : PCT_DIRECT_ACCESS : ITYP_OWNER : ITYP_NAME : PARAMETERS : GLOBAL_STATS : NO DOMIDX_STATUS : DOMIDX_OPSTATUS : FUNCIDX_STATUS : JOIN_INDEX : NO ----------------- PL/SQL 过程已成功完成。 Zianed Version 1.1 15
  • 16. LINARY@testjoe.us.oracle.com> LINARY@testjoe.us.oracle.com>ALTER TABLE emp DROP PRIMARY KEY; 表已更改。 LINARY@testjoe.us.oracle.com> 3.5、Foreign Key约束 子表的对应的列上的值,要么为父表上对应的值,要么为空。 外部键约束保护的数据列中 NULL 值的处理可能产生不可预料的结果。ORACLE 使用 ISO standar Match None 规则增强外部键约束,这个规则规定如果任何外部键作用的数据列包含 有一个 NULL 值,那么任何保留该键的数据列在父表中没有匹配值。 ON DELETE 子句标识 ORACLE 父记录(parent record)被删后,子记录的行为。默认情况下 禁止在子记录存在值时删除父记录。 LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_fk_deptno FOREIGN KEY(deptno) REFERENCES dept(deptno) ON DELETE SET NULL; ALTER TABLE emp ADD CONSTRAINT emp_fk_deptno FOREIGN KEY(deptno) REFERENCES dept(deptno) ON DELETE SET NULL * ERROR 位于第 1 行: ORA-02270: 此列列表的唯一或主键不匹配 LINARY@testjoe.us.oracle.com>select * from dept; DEPTNO DNAME LOC ---------- -------------- ------------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON LINARY@testjoe.us.oracle.com>ALTER TABLE dept ADD CONSTRAINT dept_uiq_deptno UNiQUE(deptno); 表已更改。 LINARY@testjoe.us.oracle.com>ALTER TABLE emp ADD CONSTRAINT emp_fk_deptno FOREIGN KEY(deptno) REFERENCES dept(deptno) ON DELETE SET NULL; Zianed Version 1.1 16
  • 17. 表已更改。 LINARY@testjoe.us.oracle.com> 4、延迟约束检查 延迟约束检验(Deferred Constraint Checking) 约束检验分两种情况,一种是立即约束检验(immediately checking) ,在每一条语句结 束 后 立 即 检 验 数 据 是 否 满 足 约 束 条 件 ; 另 一 种 是 延 迟 约 束 检 验 ( Deferred Constraint Checking),在事务处理完成之后对数据进行检验。默认时是 Oracle 约束检验是立即检验 (immediately checking),如果不满足约束将立即得到一条错误信息,但用户可以通过 SET CONSTRAINT 语句选择延迟约束检验。语法如下: SET CONSTRAINT constraint_name|ALL DEFERRED|IMMEDIATE ; LINARY@testjoe.us.oracle.com>SET CONSTRAINT ALL DEFERRED; 约束条件已设置。 LINARY@testjoe.us.oracle.com>SET CONSTRAINT ALL IMMEDIATE; 约束条件已设置。 LINARY@testjoe.us.oracle.com> Reference: Data Integrity http://download.oracle.com/docs/cd/B28359_01/server.111/b28318/data_int.htm#i6686 CREATE TABLE http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_7002.htm#i209533 ALTER TABLE http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_3001.htm#CJAHH IBI http://tahiti.oracle.com/ http://www.databasedesign-resource.com/enabling-and-disabling-oracle-constraints.html http://ss64.com/ora/syntax-constraints.html Zianed Version 1.1 17