1、实验:触发器一、实验目的与任务目的:旨在训练学生创建各种类型的触发器。任务:根据需求,创建符合条件的触发器。任务1:有“Student”和“Department”表,假设学生表中插入一条学生记录,则相应系人数加1,如果总人数超过150人,则拒绝插入该学生信息。create trigger trginsertStudent on studentfor insertasdeclare total intdeclare DepID intselect DepID=DepID from insertedselect total=total from Department where DepID = D
2、epIDif(total=150)beginrollback transactionendelsebeginupdate Department set total=total+1 where DepID=DepIDend执行:insert into student values(A00016,gongshi,18,女,北京市,80,2)任务2:有“Student”和“Department”表,创建触发器,如果有学生转系,则相应系人数也一并修改。create trigger trgtransDepartment on Studentfor updateasdeclare orignDepID i
3、ntdeclare NewDepID intselect orignDepID=DepID from deletedselect NewDepID=DepID from insertedupdate Department set total=total+1 where DepID=NewDepIDupdate Department set total=total-1 where DepID=orignDepID执行:update Student set DepID=2 where StuName=Tom任务3:在“Department”表中创建一个INSERT触发器,如果插入记录的院系名称在“
4、系”表中已存在,则不执行插入操作,并提示用户。create trigger trginsertDep on Departmentinstead of insertasdeclare DepName varchar(20)declare DepID intdeclare total intselect DepName=DepName from insertedselect DepID=DepID from insertedselect total=total from insertedif exists(select * from Department where DepName=DepName
5、)beginprint该系已存在rollback transactionendelsebegininsert into Department values(DepID,DepName,total)end执行:insert into department values(3,music,100)insert into department values(4,math,100)任务4:在学生表上创建更新触发器,当学生更新其他字段时,提示用户更新成功;如果更新了姓名,则让更新操作回滚。create trigger trgupName on Studentfor updateasif update(St
6、uName)beginrollback transactionprint禁止修改姓名endelseprint修改成功执行:update Student set StuName=gong where StuID=A00001update Student set StuScore=95 where StuID=A00001任务5:有“Student”和“Department”表,如删除某个系,则相应的学生全部删除。create trigger trgdeleteDep on Departmentinstead of deleteasdeclare DepID intselect DepID=Dep
7、ID from deleteddelete from SC where StuID in (select StuID from Student where DepID=DepID)delete from Student where DepID=DepIDdelete from Department where DepID=DepID执行:delete from Department where DepID=1三、内容与要求 课题名称触发器 (一)课题内容 按照任务1至任务5逐步完成,完成后学生可以创建各种类型的触发器。 (二)课题要求按照实验任务书逐步完成实验(三)考核及报告要求 1. 考核能独立完成任一项任务。2. 报告要求提交一份完整的实验报告,实验报告中详细给出每个任务的解决方案,解决方案后附带每个任务的实验结果。四、主要仪器设备硬件:PC机软件:SQL SERVER 2005