Sql约束用于限制加入表的数据类型sql
添加方式:spa
一、建立表时Create Table规定约束code
二、在表建立后经过Alter Table添加blog
sql约束有如下几种:rem
Not Null : 不接受null值,不向该字段添加值,就没法插入新记录或更新记录table
Unique:惟一标识,每一个表中能够有多个unique约束,不必定是一个列class
Create table student ( ID int not null, Name varchar(255), age int, Address varchar(255), Constraint personID unique(ID,Name) )
Primary Key:惟一标识,每一个表中只能有一个primary key约束,不必定是一个列,能够是多个列共享一个主键test
存在表的状况下增长主键约束:
Alter table student
add constraint PersonID primary key(ID)
删除主键
Alter table Student
Drop Primary Key
咱们在每次插入新记录时,一般但愿能够自动的建立主键字段的值,可使用auto-increment主键数据类型
Create Table Persons ( Id int not null auto_increment, primary key(Id) )
auto_increment的值默认是从1开始,更改默认值im
Alter table person auto_increment=100
Foreign Key:外键用于预防破坏表之间链接的动做,也能够防止非法数据插入外键列
Create Table Grade ( ID int, StudentName Varchar(255), num int, Foreign key (StudentName) references Student (name) )
两张表已经存在的状况下: Alter table Grade add foreign key (StudentName) references Student(name)
删除外键 Alter table Grade drop foreign key StudentName
Check:限制列中值的范围
添加Check 约束 Create Table Grade ( ID int, StudentName varchar(255), num int check (num <100) ) 或: Create Table Grade ( ID int, StudentName varchar(255), num int , constraint fc_n check (num <100 and num > 0) ) 或: Alter Table Grade add constraint fc_n check (num > 0)
Default:用于向列中插入默认值,若是没有规定其余值,会将默认值添加到全部的新记录中
添加默认值 Create Table test ( test1 int default ‘aaaa’ ) 或 Alter table test alter column test1 set default 'aaa'