实验3:在表上建立不同类型的约束
约束就是指对插入数据的各种限制,例如:人员的姓名不能为空,人的年龄只能在0~150岁之间。约束可以对数据库中的数据进行保护。约束可以在建表的时候直接声明,也可以为已建好的表添加约束。
约束(constraint)
保证数据的有效
保证数据的安全
可以自己书写代码
使用触发器
使用Oracle提供的五类约束
该实验的目的是掌握oracle提供的五种约束.
? Not null
定义在表的列上,表明该列必须要有值,不能为null
可以在建立表的时候说明
也可以在表建立后修改为not null
可以给约束指定名称。
如果不指定名称,数据库会给一个系统自动指定名称,SYS_C#######
User_constraints,user_cons_columns可以查看到约束的信息
建立表的时候指定not null约束
SQL> CREATE TABLE person
2 (
3 pid NUMBER ,
4 name VARCHAR(30) NOT NULL
5 ) ;
Table created
SQL> -- 插入数据
SQL> INSERT INTO person(pid,name) VALUES (11,'张三');
1 row inserted
SQL> INSERT INTO person(pid) VALUES (12);
INSERT INTO person(pid) VALUES (12)
ORA-01400: cannot insert NULL into ("SCOTT"."PERSON"."NAME")
SQL> -- 错误的数据,会受到约束限制,无法插入
SQL> create table t1 (name char(9) not null,
2 telenum char(8) constraint t1_tele_nl not null);
Table created
SQL> desc t1;
Name Type Nullable Default Comments
------- ------- -------- ------- --------
NAME CHAR(9)
TELENUM CHAR(8)
建立表的时候指明非空约束,一个是系统命名,一个是我们命名。
SQL> select CONSTRAINT_NAME,CONSTRAINT_type,TABLE_NAME,
column_name from user_constraints natural join user_cons_columns;

我们通过数据字典来验证我们的实验结果。
建立表后指定not null约束。要使用modify语法。你不指定名称,数据库自己命名。
SQL> drop table t1;
Table dropped
SQL> create table t1 as select * from dept;
Table created
SQL> alter table t1 modify(dname not null);
Table altered
SQL> desc t1;
Name Type Nullable Default Comments
------ ------------ -------- ------- --------
DEPTNO NUMBER(2) Y
DNAME VARCHAR2(14)
LOC VARCHAR2(13) Y
唯一约束UNIQUE
列的值不能重复
可以为NULL
是用索引来维护唯一的
索引的名称和约束的名称相同
建立表的时候指定UNIQUE约束
SQL> DROP TABLE person ;
Table dropped
SQL> CREATE TABLE person
2 (
3 pid NUMBER PRIMARY KEY NOT NULL ,
4 name VARCHAR(30) NOT NULL ,
5 tel VARCHAR(50) UNIQUE
6 ) ;
Table created
SQL>
SQL> -- 插入数据
SQL> INSERT INTO person(pid,name,tel) VALUES (11,'张三','1234567');
1 row inserted
SQL> -- 电话重复了
SQL> INSERT INTO person(pid,name,tel) VALUES (12,'李四','1234567');
INSERT INTO person(pid,name,tel) VALUES (12,'李四','1234567')
ORA-00001: unique constraint (SCOTT.SYS_C005400) violated
SQL>
建立表之后指定UNIQUE约束
SQL> create table t1 as select * from dept;
Table created
SQL> alter table t1 add constraint u_dname unique (dname);
Table altered

Check检测约束
条件约束,插入的数据必须满足某些条件
例如:人员有年龄,年龄的取值只能是0~150岁之间
SQL> DROP TABLE person ;
Table dropped
SQL> CREATE TABLE person
2 (
3 pid NUMBER PRIMARY KEY NOT NULL ,
4
4 name VARCHAR(30) NOT NULL ,
5 tel VARCHAR(50) NOT NULL UNIQUE ,
6 age NUMBER CHECK(age BETWEEN 0 AND 150)
7 ) ;
Table created
SQL> -- 插入数据
SQL> INSERT INTO person(pid,name,tel,age) VALUES (11,'张三','1234567',30);
1 row inserted
SQL> -- 年龄的输入错误
SQL> INSERT INTO person(pid,name,tel,age) VALUES (12,'李四','2345678',-100);
INSERT INTO person(pid,name,tel,age) VALUES (12,'李四','2345678',-100)
ORA-02290: check constraint (SCOTT.SYS_C005405) violated
SQL>
