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

2 篇文章 0 订阅
1 篇文章 0 订阅
数据库中的五种约束及其添加方法 五大约束 
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)。  
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值