數(shù)據(jù)完整性概念:能確保存儲在數(shù)據(jù)庫中數(shù)據(jù)的準(zhǔn)確性和一致性
完整性約束的類型
常用三種類型的約束保證數(shù)據(jù)完整性:
- 保證列值符合規(guī)定要求:域(列)完整性
- 要求表中所有的行唯一:實(shí)體完整性
- 要求兩表相同字段具有一致性:引用完整性
實(shí)體完整性
作用:保證實(shí)體具有唯一標(biāo)識
方法:主鍵約束、標(biāo)識列、唯一約束
主鍵約束與唯一約束
- 添加約束的基本語法
alter table 表名 add constraint 約束名 約束類型 具體的約束說明
- 約束名的取名規(guī)則推薦采用:約束類型_約束字段
主鍵(Primary Key)約束:如PK_StudentId
唯一(Unique Key)約束:如UQ_StudentIdNo
use dbname
go
--創(chuàng)建“主鍵”約束primary key
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)
--創(chuàng)建唯一約束unique
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)
域完整性
作用:保證實(shí)體屬性值符合規(guī)范要求
方法:檢查約束、限制數(shù)據(jù)類型、默認(rèn)值、非空約束
檢查約束與默認(rèn)約束
約束名的取名規(guī)則:
- 檢查(Check Key)約束:如CK_Age
- 默認(rèn)(Default Key)約束:如DF_StudentAddress
--創(chuàng)建檢查約束
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)
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)
--創(chuàng)建默認(rèn)約束
if exists(select * from sysobjects where name='df_StudentAddress')
alter table Students drop constraint df_StudentAddress
alter table Students add constraint df_StudentAddress default('地址不詳') for StudentAddress
--使用默認(rèn)值插入數(shù)據(jù)
insert into Students (StudentName,Gender,Birthday,Age,StudentIdNo ,PhoneNumber,
StudentAddress,ClassId)
values('李小璐','女','1989-01-12',24,120229198901121315, '13099012876',default,1)
引用完整性
作用:保證兩張表相同屬性值的一致性
約束方法:外鍵約束
insert into StudentClass (ClassId,ClassName) values(1,'軟件班')
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)
數(shù)據(jù)表的使用總結(jié)
主鍵的選擇
- 最少性原則:盡量選擇單個(gè)鍵作為主鍵。
- 穩(wěn)定性原則:盡量選擇數(shù)值更新少的列最為主鍵。
外鍵使用
- 要求數(shù)據(jù)類型、數(shù)據(jù)長度必須與對應(yīng)的主鍵表字段完全一致。
- 添加數(shù)據(jù)時(shí),要首先添加主鍵表,再添加外鍵表。
- 刪除數(shù)據(jù)時(shí),要首先刪除外鍵表數(shù)據(jù),再刪除主鍵表數(shù)據(jù)。
完整數(shù)據(jù)庫創(chuàng)建步驟
建庫→建表→主鍵約束→域完整性約束→外鍵約束
插入數(shù)據(jù)的過程
驗(yàn)證主鍵、主外鍵關(guān)系、檢查約束......→插入成功