1.check约束 范围
-- 建表时定义性别取值为“男或女” 默认为“男”
-- 年龄在14到65之间(14,65)
-- in (值1,值2,值3...值n) 属于值1到值n其中之一(详见聚集函数)create table Student(
Sno Char(7) primary key,--学号
Sname Char(10) not null,--学生姓名
Ssex Char(2) check(Ssex in('男','女')) default '男'not null,--性别
Sage Smallint check(Sage>14 and Sage<65)--年龄
);
2.外码违约处理方式为删除级联或更新级联
-- 成绩表Sno(学号)关联学生表Sno
-- 成绩表Cno(课程号)关联课程表Cno
-- 设置两个外键违约处理方式为删除级联和更新级联create table Cj(
Sno Char(7),--学号
Cno Char(1),--课程号
Grade Decimal(4,1) check(Grade>0 and Grade<100),--成绩
primary key(Sno,Cno),
foreign key(Sno) references Student(Sno) on delete cascade on update cascade,
foreign key(Cno) references Course(Cno) on delete cascade on update cascade
);
为外键设置了删除级联和更新级联,当处理主表时外表受到牵连。即:更新(删除)主表值-》外表相应值也更新(被删除)
3.添加,删除,修改约束
3.1添加约束
alter table 表名 add constraint 约束名 约束表达式
alter table Course add constraint CK_Course_Credit check(Credit in (1,2,3,4));
3.2删除约束
alter table 表名 drop 约束名
alter table Course drop CK__Course__Credit__164452B1;
3.3修改约束
先删除 再添加