1. CHECK约束介绍
- 就是检查约束,用于限定每一列能够输入的值,以保证数据的正确性。
- 例如:下面表中的性别,我们限定其为:男和女。那么后面的性别只有这两个值。限定死了。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/84db099573a8599a78083a6f67a90d0c.png)
2. 添加CHECK约束
2.1 在建表时添加约束
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/29128487a54e716cfe471928fbfc0511.png)
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://i-blog.csdnimg.cn/blog_migrate/aa229868e82522267f5e2722c77012b8.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;