数据库完整性设计

1.主键约束(PRIMARY KEY)

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

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)

2.唯一性约束(UNIQUE)

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

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,如果不满足检查约束的条件数据不可被插入或修改

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则自动存为默认值

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字段

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

  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Maybe_ch

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值