前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >数据库完整性设计

数据库完整性设计

作者头像
MaybeHC
发布2024-04-23 18:25:57
1010
发布2024-04-23 18:25:57
举报
文章被收录于专栏:技术之路技术之路

1.主键约束(PRIMARY KEY)

1) 主键用于唯一地标识表中的每一条记录,可以定义一列或多列为主键。 2) 是不可能(或很难)更新. 3) 主键列上没有任何两行具有相同值(即重复值),不允许空(NULL). 4) 主健可作外健,唯一索引不可; 例如给表Students的StudentId字段添加主键约束

代码语言:javascript
复制
if exists(select * from sysobjects where name='pk_StudentId')
alter table Students drop constraint pk_StudentId
alter table Students add constraint pk_StudentId primary key(StudentId)
代码语言:javascript
复制

2.唯一性约束(UNIQUE)

1) 唯一性约束用来限制不受主键约束的列上的数据的唯一性,用于作为访问某行的可选手段,一个表上可以放置多个唯一性约束. 2) 只要唯一就可以更新. 3) 即表中任意两行在 指定列上都不允许有相同的值,允许空(NULL). 4) 一个表上可以放置多个唯一性约束 例如给表Students 的StudentIdNo字段添加唯一性约束

代码语言:javascript
复制
if exists (select * from sysobjects where name = 'uq_StudentIdNo')
alter table Students drop constraint uq_StudentIdNo
alter table Students add constraint uq_StudentIdNo unique (StudentIdNo)

3.检查约束(Check)

下面是两个检查性约束的例子,第一个限制Age 字段范围为18-25,,第二个限制PhoneNumber长度为11,如果不满足检查约束的条件数据不可被插入或修改

代码语言:javascript
复制
if exists (select * from sysobjects where name = 'ck_Age')
alter table Students drop constraint ck_Age
alter table Students add constraint ck_Age check(Age between 18 and 25) --年龄18-25

if exists (select * from sysobjects where name = 'ck_PhoneNumber')
alter table Students drop constraint ck_PhoneNumber
alter table Students add constraint ck_PhoneNumber check(len(PhoneNumber)=11)
--限定PhoneNumber长度为11位

4.默认约束(Default)

给字段设置默认值 给StudentAddress设置默认值,如果插入时不输入StudentAddress则自动存为默认值

代码语言:javascript
复制
if exists (select * from sysobjects where name ='dt_StudentAddress')
alter table Students drop constraint dt_StudentAddress
alter table Students add constraint dt_StudentAddress default ('地址不详') for StudentAddress

5.外键约束(Foreign Key)

建立两表间的关系并引用主表的列 Students表的ClassId字段引用StudentClass的ClassId字段

代码语言:javascript
复制
if exists (select * from sysobjects where name = 'fk_ClassId')
alter table Students drop constraint fk_ClassId
alter table Students add constraint fk_ClassId foreign key(ClassId) references StudentClass(ClassId)

约束名的取名规则推荐采用:约束类型_约束字段 主键约束 :如 PK_StudentId 唯一性约束 :如 UQ_StudentIdNo 检查约束:如 CK_Age 默认约束:如 DT_StudentAddress 外键约束:如 FK_Age

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2024-04-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1.主键约束(PRIMARY KEY)
  • 2.唯一性约束(UNIQUE)
  • 3.检查约束(Check)
  • 4.默认约束(Default)
  • 5.外键约束(Foreign Key)
相关产品与服务
数据库
云数据库为企业提供了完善的关系型数据库、非关系型数据库、分析型数据库和数据库生态工具。您可以通过产品选择和组合搭建,轻松实现高可靠、高可用性、高性能等数据库需求。云数据库服务也可大幅减少您的运维工作量,更专注于业务发展,让企业一站式享受数据上云及分布式架构的技术红利!
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档