数据库中的五种约束及其添加方法 五大约束

来源:互联网 发布:淘宝红包链接怎么复制 编辑:程序博客网 时间:2024/06/08 15:32
数据库中的五种约束及其添加方法 五大约束 
1.—-主键约束(Primay Key Coustraint) 唯一性,非空性 
2.—-唯一约束 (Unique Counstraint)唯一性,可以空,但只能有一个 
3.—-检查约束 (Check Counstraint) 对该列数据的范围、格式的限制(如:年龄、性别等) 4.—-默认约束 (Default Counstraint) 该数据的默认值 
5.—-外键约束 (Foreign Key Counstraint) 需要建立两表间的关系并引用主表的列 五大约束的语法示例 
1.—-添加主键约束(将stuNo作为主键) alter table stuInfo 
add constraint PK_stuNo primary key (stuNo) 
2.—-添加唯一约束(身份证号唯一,因为每个人的都不一样) alter table stuInfo 
add constraint UQ_stuID unique(stuID) 
3.—-添加默认约束(如果地址不填 默认为“地址不详”) alter table stuInfo 
add constraint DF_stuAddress default (‘地址不详’) for stuAddress 4.—-添加检查约束 (对年龄加以限定 15-40岁之间) alter table stuInfo 
add constraint CK_stuAge check (stuAge between 15 and 40)  
alter table stuInfo 
add constraint CK_stuSex check (stuSex=’男’ or stuSex=’女′)  
5.—-添加外键约束 (主表stuInfo和从表stuMarks建立关系,关联字段stuNo)  
alter table stuInfo 
add constraint FK_stuNo foreign key(stuNo)references stuinfo(stuNo)  
约束(Constraint)是Microsoft SQL Server 提供的自动保持数据库完整性的一种方法,定义了可输入表或表的单个列中的数据的限制条件(有关数据完整性的介绍请参见第9 章)。在SQL Server 中有5 种约束:主关键字约束(Primary Key Constraint)、外关键字约束(Foreign Key Constraint)、惟一性约束(Unique Constraint)、检查约束(Check Constraint)和缺省约束(Default Constraint)。  
原创粉丝点击