SQL Server中的约束(六种约束):
https://blog.csdn.net/qq_43551373/article/details/87865739;
SQL_Server 检查约束:
https://blog.csdn.net/gengkui9897/article/details/89440490;
检查约束的几种创建方式(详细看上面的链接):
限定输入:
1、
use dbmyFirstDatabase
create table t_test
(
ID int identity(1,1) primary key,
name nvarchar(10) not null,
sex char(2) check(sex='男' or sex='女') not null
)
2、
use dbmyFirstDatabase
create table test
(
ID int identity(1,1) primary key,
name nvarchar(10) not null,
sex char(2)
)
--添加约束
alter table test
add constraint CK_test_sex check(sex='男' or sex='女')
3、(效果和2相同)
use dbmyFirstDatabase
alter table test
add constraint CK_test_sex check(sex in('男','女'))
范围限定:
1、
use dbmyFirstDatabase
create table test
(
ID int identity(1,1) primary key,
name nvarchar(10) not null,
sex char(2) ,
age int check(age>=0 and age <=100)
)
2、
use dbmyFirstDatabase
create table test
(
ID int identity(1,1) primary key,
name nvarchar(10) not null,
sex char(2) ,
age int
)
--添加约束
alter table test
add constraint CK_test_age check(age>=0 and age <=100)
3、(效果和2相同)
use dbmyFirstDatabase
alter table test
add constraint CK_test_age check (age between 0 and 100)