约束的类型

约束的类型:

主键约束: 要求主键列不能为空,要求主键列唯一

非空约束: 要求该列不能存在空值

唯一约束: 要求该列的值必须唯一的,允许为空,但只能出一个空值

检查约束: 限制某列取值的范围是否合适

默认约束: 设计某列的默认值

外键约束: 用于在两表之间建立关系,需要指定引用主表是哪一列

 

主键约束与唯一约束的区别

1.主键约束所在的列不允许有空值,唯一约束所列允许为空值

2.每个表中可以有一个主键,多个唯一约束

 

语法

alter table 表名

add constraint 约束名 约束类型 具体的约束说明

约束名的取名规则推荐采用: 约束类型_约束列

主键[primary key]约束 :如 PK_userid

唯一[unique key] 约束 :如 UQ_userid

默认[default key] 约束 :如 DF_userid

检查[check key]  约束 :如 CK_userid

外键[foreign key] 约束 :如 FK_userid

 

 

--添加主键约束   
Alter Table stuInfo   
Add Constraint  PK_stuNO primary Key(stuNo)   
---添加唯一约束   
Alter Table stuInfo   
Add Constraint UQ_stuID unique(stuID)   
---添加默认约束   
Alter Table stuInfo   
Add Constraint DF_stuAddress default('地址不详') for stuAddress   
---添加检查约束   
Alter Table stuInfo   
Add Constraint CK_stuAge check(stuAge between 15 and 40)   
---添加外键约束   
Alter Table stuMarks   
Add Constraint FK_stuNo foreign key(stuNo) references stuInfo(stuNo)  

 

在创建表的时候同时添加约束的写法:
use stuDB   
go   
if exists(select * from Sysobjects where name = 'stuInfo')   
drop table stuInfo   
go   
create table stuInfo   
(   
     stuName varchar(20) not null primary key(stuName)    
,stuID int not null unique(stuID)   
,stuAddress varchar(20) not null default('地址不详')   
,stuAge int not null check(stuAge between 15 and 40)  

 

posted @ 2018-03-30 10:54  WhiteSpace  阅读(1090)  评论(0编辑  收藏  举报