码迷,mamicode.com
首页 > 其他好文 > 详细

约束的类型

时间:2018-03-30 12:15:37      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:address   uid   exist   限制   color   默认   ref   主键约束   主键   

约束的类型:

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

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

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

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

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

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

 

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

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)  

 

约束的类型

标签:address   uid   exist   限制   color   默认   ref   主键约束   主键   

原文地址:https://www.cnblogs.com/xiaowie/p/8674980.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!