文档详情

第五章数据库的完整性解析.ppt

发布:2016-03-17约字共23页下载文档
文本预览下载声明
An Introduction to Database System 第五章 数据库完整性 约束 check约束 check 约束(续) default约束、删除约束 规则 规则(续) 默认值 完整性的违约处理 参照完整性的违约处理 触发器 触发器(续) 触发器执行顺序 触发器的递归触发 这个功能怎么实现? deleted表和inserted表 deleted表和inserted表示例 转系历史数据的跟踪存储 问题的解决办法 实现CS_S视图的数据插入 实现Course表的违约处理 实现Course表的违约处理(续) 触发器小结 * 数据库的安全性是尽可能保证非法用户不破坏数据的正确性。 数据库的完整性是尽可能保证合法用户不破坏数据的正确性。 数据库的完整性是为了尽可能防止数据库中存在不符合语义的数据。 问题:你还记得实体完整性约束和参照完整性约束是怎么回事吗? 为此,DBMS需要完成: 提供定义完整性约束条件的机制 提供完整性检查的方法 违约处理 完整性分类:实体完整性、参照完整性和用户定义完整性。 约束:就是一种强制性的规定。 1、建立非空约束。 alter table course alter column credit smallint not null 其中,必须给出列的类型。 SQL Server的六种约束: not null 非空约束 check 检查约束 unique 唯一约束 primary key 主码约束 foreign key 外码约束 default 默认约束 约束的建立: 在创建表的同时建立 在已有表上建立 注意:若表中已有数据,则建立约束时可能会失败。 2、建立唯一约束。 alter table course add constraint UQ_cname unique(cname) 其中:constraint关键词即对该约束进行命 名,即UQ_cname是约束名。 注意:对每个约束都进行命名是个好习惯 注意:非空约束不能命名。删除某列的非空约束语句为: alter table course alter column credit smallint null 1、创建表时建立check约束。 create table stu ( sno char(9) constraint PK_stu primary key, name char(8) not null, age smallint constraint c_age check(age 0 and age 100) ) 逻辑表达式 问题:此时age列值可以是空吗? 或 create table stu ( sno char(9), name char(8) not null, age smallint, constraint PK_stu primary key (sno), constraint c_age check (age 0 and age 100) ) 2、在表中增加check约束 alter table student add constraint c_age check(Sage 0 and Sage 100) check约束可用于建立表中属性取值上的某些约束关系。 答:可以是空。 3、规定性别的取值只能是男或女。 4、check的表达式可以包含多个属性。如规定CS系学生必须 25岁以下。 问题:此时ssex列值可空吗? alter table student add constraint c_ssex check(ssex in (男, 女)) 答:可以是空。问题:若要求该列取值同时不可为空,则如何表达? alter table student add constraint c_cs_age check(sdept cs or sage = 25) 问题:你知道这个约束条件是怎么得到的吗? alter table student add constraint c_ssex check(ssex in (男, 女) and ssex is not null) default约束:可以对列设置默认值。如对性别列默认取值为男。 1、创建表时建立default约束。 create table student ( sno char(9) primary key, ssex char(2)
显示全部
相似文档