主键 primary key
唯一 unique
检查 check
默认 default
外键 foreign key
1.添加约束
(1)约束和表分开的一种
ALTER TABLE 表名 ADD CONSTRAINT 约束名 约束类型 具体的约束说明
示例:
--添加外键
alter table StuMarks
add constraint fk_StuID
foreign key (StuID) references StuInfo(StuID)
--添加主键
alter table StuMarks
add constraint pk_StuMarks primary key (ExamNo)
--添加检查约束
alter table StuMarks
add constraint ck_Score
check(Score>=0 and Score<=100)
(2)建表时同时建约束
示例:
create table StuMarks
(
ExamNo int not null primary key ,
StuID int not null references StuInfo(StuID),
Score int not null check(Score>=0 and Score<=100)
)
2.删除约束
语法:ALTER TABLE 表名
DROP CONSTRAINT 约束名
3.自增长
IDENTITY(初始值,递增值)