一、实验目的
(1)理解视图的概念。
(2)掌握创建视图、测试、加密视图的方法。
(3)掌握更改视图的方法。
(4)掌握用视图管理数据的方法。
二、实验内容
-
创建视图
(1)创建一个名为stuview1的水平视图,从Student_info数据库的student表中查询出所有男学生的资料。并在创建视图时使用with check option。create view stuview1 as select * from Student where Sex='男' with check option;
(2)创建一个名为stuview2的投影视图,从数据库Student_info的Course表中查询学分大于3的所有课程的课程号、课程名、总学时,并在创建时对该视图加密。
create view stuview2(cno,cname,total_perior) with encryption as select Cno,Cname,Total_perior from Course where Credit>3;
(3)创建一个名为stuview3的视图,能检索出“051”班所有女生的学号、课程号及相应的成绩。
create view stuview3(sno,cno,grade) as select Student.Sno,Cno,Grade from SC,Student where SC.Sno=Student.Sno and Classno='051' and Sex='女';
(4)创建一个名为stuview4的视图,能检索出每位选课学生的学号、姓名、总成绩。
create view stuview4(classno, sname,sumGrade) as select Classno,Sname,sum(Grade) from Student,SC where Student.Sno=SC.Sno group by Student.Sname,Classno;
-
查询视图的创建信息及视图中的数据
(1)查看视图stuview1的创建信息。
方法1:通过系统存储过程sp_help查看。sp_help 'stuview1'
方法2:通过查询表sysobjects。
select * from sysobjects where xtype='V' and name ='stuview1';
(2)查看视图的定义脚本。
方法1:通过系统存储过程sp_helptext。sp_helptext 'stuview1'
方法2:通过查询表sysobjects和表syscomments。
(提示:视图的名称保存在表sysobjects的name列,定义脚本保存在表syscomments的text列)。select name ,text from sysobjects,syscomments where sysobjects.id=syscomments.id and name='stuview1';
(3)查看加密视图stuview2的定义脚本。
exec sp_helptext 'stuview2'
-
修改视图的定义
修改视图stuview2,使其从数据库Student_info的Course表中查询总学时大于60的所有课程的课程号、课程名、学分。alter view stuview2(cno,cname,credit) as select Cno,Cname,Credit from Course where Total_perior>60;
-
视图的更名与删除
(1)将视图stuview4更名为stuv4。sp_rename stuview4,stu4;
(2)将视图stuv4删除。
drop view stu4;
-
管理视图中的数据
(1)从视图stuview1查询出班级为“051”、姓名为“张虹”的资料。select * from stuview1 where Classno='051' and Sname='张虹';
(2)向视图stuview1中插入一行数据。学号:20110005,姓名:许华,班级:054,性别:男,家庭住址:南京,入学时间:2011/09/01,出生年月:1983/01/09。
原Student表中的内容有何变化?insert into stuview1 values('20110005','许华','男','1983-01-09','054','2011-09-01','南京','计算机系',null)
在Student表中成功插入了一行数据
思考:如向视图stuview1中插入一行数据。学号:20110006,姓名:赵静,班级:054,性别:女,家庭住址:南京,入学时间:2011/09/01,出生年月:1983/11/09。会出现什么样的结果?原Student表中的内容有何变化?
insert into stuview1 values('20110006','赵静','女','1983-11-09','054','2011-09-01','南京','计算机系',null);
插入失败,因为视图stuview1有约束
试图进行的插入或更新已失败,原因是目标视图或者目标视图所跨越的某一视图指定了 WITH CHECK OPTION,而该操作的一个或多个结果行又不符合 CHECK OPTION 约束。
(3)修改视图stuview1中的数据。
将stuview1中054班、姓名为“许华”同学的家庭地址改为“扬州市”。
原Student表中的内容有何变化?update stuview1 set Home_addr='扬州市' where Sname='许华' and Classno='054';
在Student表中也发生了相应的改变
(4)删除视图stuview1中班级为054、姓名为“许华”的同学的记录。
原Student表中的内容有何变化?delete from stuview1 where Classno='054' and Sname='许华';