1. CHECK约束介绍
- 就是检查约束,用于限定每一列能够输入的值,以保证数据的正确性。
- 例如:下面表中的性别,我们限定其为:男和女。那么后面的性别只有这两个值。限定死了。
![在这里插入图片描述](https://img-blog.csdnimg.cn/c752643dad394774b46860aa8da6942a.png)
2. 添加CHECK约束
2.1 在建表时添加约束
![在这里插入图片描述](https://img-blog.csdnimg.cn/884923ef3e31409793ed0d15f57e7746.png#pic_center)
2.1.1 案例
create table tb_students(
stu_num char(5) not null,
stu_name varchar(10) not null,
stu_sex char(2) not null,
primary key(stu_num),
constraint ck_student_sex CHECK(stu_sex='男' or stu_sex='女')
);
- 如果建立学生信息表时,想限定性别为“男”或“女”、限定学生年龄在[6,30],该怎么做?如下示:
create table tb_students(
stu_num char(5) not null,
stu_name varchar(10) not null,
stu_sex char(2) not null,
stu_age number(2) not null,
primary key(stu_num),
constraint ck_student_sex CHECK(stu_sex='男' or stu_sex='女'),
constraint ck_student_age check(stu_age between 6 and 30)
);
2.2 建表后,再添加约束
![在这里插入图片描述](https://img-blog.csdnimg.cn/342886863e034e8d96514d9ef78704b4.png)
2.2.1 案例
create table tb_students(
stu_num char(5) not null,
stu_name varchar(10) not null,
stu_sex char(2) not null,
stu_age number(2) not null,
primary key(stu_num)
);
- 接下来,为表中添加CHECK约束,限定性别为“男”或“女”:
alter table tb_students
add constraint ck_student_sex Check(stu_sex='男' or stu_sex='女');
3. 删除CHECK约束
- 删除学生信息表中的ck_student_sex约束:
alter table tb_students
drop constraint ck_student_sex;