1、提示:D_Info表中存储了院系代码D_ID,而St_Info表中学号字段St_ID的前两位与之对应,则D_Info表与St_Info表之间的联系通过这两个字段的运算构成连接条件。1.分别执行存储过程getPractice,查询“法学院”和“材料科学与工程学院”的学生中参与“实践”课程的所有学生学号、姓名、所学课程编号和课程名称。create procedure getPractice D_Name varchar(30) output asbeginif not exists (select *from D_Infowhere D_Name= D_Name )print 对不起,该院系不存在
2、elseselect st_info.St_ID,C_Info.C_No,C_Namefrom s_c_info inner join st_info on st_info.St_ID=s_c_info.st_id inner join C_Info on s_c_info.c_no=C_Info.C_Nowhere st_info.St_ID in( select St_ID from st_info join D_Info on D_Info.D_ID =left(st_info.St_ID,2) where C_Info.C_Type=实践 and D_Info.D_Name= D_Na
3、me ) end go2.利用系统存储过程sp_rename将getPractice更名为getPctStuexecute sp_rename getPractice , getPctStu3.修改存储过程getPctStu,返回指定院系中参与实践课程的学生人次数,并利用该存储过程以“法学院”为输入参数验证执行的结果alter procedure getPctStu asselect st_info.St_ID,C_Info.C_No,C_Name,count (st_info.St_ID) as 人次数 group by st_info.St_ID,C_Info.C_No,C_NameGoe
4、xec getPctStu 法学院4.再修改存储过程getPctStu,返回指定院系中参与实践课程的学生人数。注:“人数”和“人次数”是不同的,对某一学生而言,如果参与了多门实践课程,则“人次数”是指其参与的课程门数,而“人数”仍为1。(二)触发器1.在studentdb数据库中建立一个具有审计功能的触发器:触发器名为tr_sc,功能要求:审计在s_c_info表中对score字段的更新和插入操作,将这些操作记录到sc_log表中,sc_log表中有如下字段:操作类型type,学号st_id,课程号c_no,旧成绩oldscore,新成绩newscore,操作员uname,操作时间udate,
5、其中操作员设定默认值为user,操作时间默认值为系统时间。create table sc_log(type varchar(4),st_id varchar(10),c_no varchar(10),oldscore int,newscore int,uname varchar(10) default user,udata datetime default getdate()create trigger tr_scon s_c_infofor insert,updateas if update(score)if(select count(*) from deleted)insert into
6、sc_log(type,st_id,c_no,oldscore,newscore)select update,s_c_info.st_id,s_c_info.c_no,i.score,d.score from s_c_info,inserted i,deleted dwhere s_c_info.st_id=i.st_id and i.st_id=d.st_idinsert into sc_log(type,st_id,c_no,newscore)insert,st_id,c_no,scorefrom insertedend3.在s_c_info表上建立一个触发器tr_updasc,用于监控对
7、成绩的更新,要求更新后的成绩不能比更新前低,如果新成绩低则取消操作,给出提示信息,否则允许更新。create trigger tr_updascafter updatedeclare cj1 int,cj2 intselect cj1=deleted.score from deletedselect cj2=inserted.score from insertedif(cj2cj1)raiserror(新成绩比老成绩低,取消操作,16,1)rollback transaction(三)查看存储过程和触发器的信息1.用sp_help查看以上建立的存储过程和触发器的基本信息sp_help tr_s
8、csp_help tr_updasc2.用sp_helptext查看存储过程和触发器的代码sp_helptext tr_scsp_helptext tr_updasc四、思考与练习1存储过程如何加密?Create procedure encrypt_thisWith encryption -加密,在存储过程添加这一语句即可ASSelect* from user_tbGO查看存储过程储存的文本:Exec sp_helptext encrypt_this下面是结果集:The projects comments have been encrypted. -对象已经被加密2触发器有什么好处和坏处?使用
9、触发器的好处:1. 自动执行。触发器在对表的数据作了任何修改(比如手工输入或者应用程序的操作)之后立即被激活。2. 级联更新。触发器可以通过数据库中的相关表进行层叠更改,这比直接把代码写在前台的做法更安全合理。3. 强化约束。触发器可以引用其它表中的列,能够实现比CHECK约束更为复杂的约束。4. 跟踪变化。触发器可以阻止数据库中未经许可的指定更新和变化。5. 强制业务逻辑。触发器可用于执行管理任务,并强制影响数据库的复杂业务规则。相对于外部程序、存储过程,触发器可以更快更高效地维护数据。滥用数据库的坏处:滥用会造成数据库及应用程序的维护困难。一个大型应用里,触发器越少越好,触发器会使编程时源码的结构被迫打乱,为将来的程序修改、源码阅读带来很大不便。
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1