扫码一下
查看教程更方便
check 约束使条件能够检查输入到记录中的值。如果条件为假,则记录违反约束并且不会被添加进表中。
例如,以下sql 语句创建一个名为 customers 的新表并添加五列。在这里,我们对 age 列添加了一个 check 约束,使 age >= 18,这样就不能添加任何 18 岁以下客户记录到 customer表中。
create table customers(
id int not null,
name varchar (20) not null,
age int not null check (age >= 18),
address char (25) ,
salary decimal (18, 2),
primary key (id)
);
如果已经创建了 customers 表,那么要向 age 列添加 check 约束,需要使用 alter table 语句来更改表。
alter table customers
modify age int not null check (age >= 18 );
我们还可以使用以下语法,它也支持在多列中添加约束
alter table customers
add constraint mycheckconstraint check(age >= 18);
要删除 check 约束,请使用以下 sql 语法。此语法不适用于 mysql。
alter table customers
drop constraint mycheckconstraint;