数据库完整性设计

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

猜你喜欢

转载自blog.csdn.net/Maybe_ch/article/details/81913186