1. CHECK 制約の概要
- これはチェック制約であり、データの正確性を保証するために各列に入力できる値を制限するために使用されます。
- 例: 以下の表の性別は、男性と女性に限定されます。すると、次の性別はこの 2 つの値のみを持ちます。制限は死んだ。
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;