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'