约束
约束用于规定表中的数据规则
如果存在违反约束的数据行为,行为会被约束终止
primary key 约束
某列的唯一标识, 每个表只能有一个primary key 约束
create table Student(ID int primary key)
或
create table Student(ID int,primary key(ID))
定义约束命名,定义多列的约束
create table Student(ID int,Name nvarchar(64),Age int,constraint PK_Student_IDName primary key(ID,Name))
这样也属于一个主键,是由ID和Name组成的
可以这样插入,只要两个都相同插入才会报错
insert into Student values(1,'West',18)insert into Student values(2,'West',18)
删除约束
alter table Studentdrop constraint PK_Student_IDName
not null约束
非空约束
create table Student(ID int,Name nvarchar(64) not null)
unique约束
某列的每行的唯一标识, 不能插入重复的数据
create table Student(ID int,Name nvarchar(64) unique)
foreign key 约束
外键约束,一个表的foreign key指向另一个表的unique
create table Student(ID int identity(1000,1) primary key,Name nvarchar(64),Age int)
新建表时设置外键
create table Score(ID int identity(1,1),StudentID int foreign key references Student(ID),CourseID int,Score float)
新建表后设置外键
create table Score(ID int identity(1,1),StudentID int,CourseID int,Score float)alter table Score add constraint FK_Score_StudentID foreign key (StudentID) references Student(ID)
check 约束
用于限制列中值的范围
限制成绩大于0,
小于或等于0时,将报错
create table Score(ID int identity(1,1),StudentID int,CourseID int,Score float,constraint CHK_Score check(Score>=0))
插入数据
insert into Score(StudentID,CourseID,Score) values(1000,1,-1)
报错:INSERT 语句与 CHECK 约束"CHK_Score"冲突。该冲突发生于数据库"School",表"dbo.Score", column 'Score'。
default约束
用于向列中插入默认值
create table Score(ID int identity(1,1),StudentID int,CourseID int,Score float default '60')
插入数据
insert into Score(StudentID,CourseID) values(1001,1)
Score字段的默认值为60,即是删除default约束后,该行数据的Score还是60,新添加的如果没有赋值则是null