Sql 约束

Sql约束用于限制加入表的数据类型

添加方式:

1、创建表时Create Table规定约束

2、在表创建后通过Alter Table添加

sql约束有以下几种:

Not Null : 不接受null值,不向该字段添加值,就无法插入新记录或更新记录

Unique:唯一标识,每个表中可以有多个unique约束,不一定是一个列

Create table student 
(
ID int not null,
Name varchar(255),
age int,
Address varchar(255),
Constraint  personID unique(ID,Name)
)

 

Primary Key:唯一标识,每个表中只能有一个primary key约束,不一定是一个列,可以是多个列共享一个主键

存在表的情况下增加主键约束:
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开始,更改默认值

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 intconstraint 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'

 

posted @ 2019-02-11 14:03  珍真小心  阅读(237)  评论(0编辑  收藏  举报