sql server约束(constraint)介绍
数据库约束是为了保证数据的完整性(正确性)而实现的一套机制
- 非空约束
- 主键约束(PK) primary key constraint 唯一且不为空
- 唯一约束 (UQ)unique constraint 唯一,允许为空,但只能出现一次
- 默认约束 (DF)default constraint 默认值
- 检查约束 (CK)check constraint 范围以及格式限制
- 外键约束 (FK)foreign key constraint 表关系
--添加主键约束
alter table Score
add constraint PK_Score primary key(sId)
--添加唯一约束
alter table student
add constraint UQ_student unique(sNo)
--添加默认约束
alter table student
add constraint DF_student default('男') for sSex
--添加检查约束
alter table student
add constraint CK_student check(sAge >=18 and sAge <=100)
alter table student
add constraint CK_Sutdent1 check(sSex='男' or sSex='女')
alter table student
add constraint CK_Student2 check(sIntime>sBirthday) --入学日期必须大于出生日期
--添加外键约束(主键表Class 外键表student)
alter table student
add constraint FK_student
foreign key(sClassId) references Class(cId) --外键student表中的sClassId来references引用主键表中的cid
on delete cascade --级联删除,添加约束的时候加上这个,删除主表的时候,会把外键对应的子表级联删除(慎用)
on update cascade --级联更新
--删除约束
alter table student
drop constraint FK_student为数据的最终存放处。