05|Oracle学习(CHECK约束)

1. CHECK约束介绍

  • 就是检查约束,用于限定每一列能够输入的值,以保证数据的正确性。
    • 例如:下面表中的性别,我们限定其为:男和女。那么后面的性别只有这两个值。限定死了。
      在这里插入图片描述

2. 添加CHECK约束

2.1 在建表时添加约束

在这里插入图片描述

2.1.1 案例
  • 建立一个学生信息表,将其中的性别用Check约束
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 建表后,再添加约束

在这里插入图片描述

2.2.1 案例
  • 建立个没有CHECK约束的学生信息表:
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;

猜你喜欢

转载自blog.csdn.net/qq_41714549/article/details/132061147