第五章完整性.ppt

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

文档评论(0)

1亿VIP精品文档

相关文档