数据库专题训练实验-------触发器
掌握触发器的分类及工作原理。
掌触发器的创建方法。
掌握触发器的使用方法。
CREATE TRIGGER tri_Delete_C ON C
AFTER DELETE
AS
DELETE FROM SC
WHERE SC.Cno IN (SELECT Cno FROM DELETED)
delete
From C
where Cno=‘C5’
CREATE TRIGGER tri_Insert_S ON S
For Insert,UPDATE
AS
if exists(select* from inserted where (Sage<18 or Sage>25))
begin
print ‘Sage不满足条件,无法插入’
rollback
End
insert into S
values
(‘S8’,‘徐小铎’,‘男’,‘28’,‘计算机’)
insert into S
values
(‘S9’,‘河马’,‘男’,‘11’,‘计算机’)
insert into S
values
(‘S10’,‘大象’,‘女’,‘20’,‘计算机’)
use XSCJ
IF EXISTS (SELECT name FROM sysobjects
WHERE name = ‘tri_Update_SC’ AND type = ‘TR’)
DROP TRIGGER tri_Update_SC
go
CREATE TRIGGER tri_Update_SC ON SC
For insert,delete,update
AS
print ‘不能随便修改成绩!’
rollback
insert into SC
values
(‘S9’,‘C9’,‘99’)
use XSCJ
go
sp_help tri_Delete_C
use XSCJ
go
sp_helptext tri_Delete_C
use XSCJ
go
exec sp_helptrigger SC
alter table SC disable trigger tri_Update_SC
use XSCJ
go
insert into SC
values
(‘S9’,‘C9’,‘99’)
use XSCJ
IF EXISTS (SELECT name FROM sysobjects
WHERE name = ‘tri_Insert_SC’ AND type = ‘TR’)
DROP TRIGGER tri_Insert_SC
go
create trigger tri_Insert_SC on SC
instead of insert
as
if exists(select * from inserted
where (Score>0 and Score<=100))
begin
insert into SC
select * from inserted
print’插入成功’
end
else
begin
rollback
print’分数插入异常,请您重复检查’
end
use XSCJ
go
insert into SC
values
(‘S9’,‘C9’,‘99’)
use XSCJ
go
insert into SC
values
(‘S9’,‘C9’,’-2’)
use XSCJ
go
insert into SC
values
(‘S9’,‘C9’,‘102’)
use XSCJ
go
if exists(select name from sysobjects
where name=‘tir_Update_S’ and type=‘TR’)
drop trigger tir_Update_S
go
create trigger tir_Update_S on S
after update
as
declare @old varchar(10) ,@new varchar(10)
select @old=Sno from deleted
select @new=Sno from inserted
if(update(Sno))
begin
update SC
set SC.Sno=@new
where SC.Sno=@old
end
else
rollback
update S
set Sno=‘S9’
where Sno=‘S10’
use XSCJ
go
if exists(select name from sysobjects
where name='tri_Delete_C ’ and type=‘TR’)
drop trigger tri_Delete_C
go
create trigger tri_Delete_C
on C
instead of delete
as
if (exists(select * from SC,deleted
where SC.Cno=deleted.Cno))
begin
print’课程被选,无法删除’
rollback
end
else
begin
delete from C where Cno in(select Cno from deleted)
End
use XSCJ
insert into C
values
(‘C6’,‘Linux’,‘小路’)
delete
from C
where Cno=‘C4’
delete
from C
where Cno=‘C6’
测试代码分为了三个部分,第一个是创建一个没有学生选课的课程(编号C6,名称LINUX,教师小路)然后通过两个测试代码对触发器tir_Delete_C进行测试;第一个测试代码:在SC中已经被选课的C4,预期会触发条件,产生“课程被选,无法删除”的提示;第二个测试代码,因为在SC中没有学生选课,所以可以顺利删除。
通过本次实验,对触发器的学习,感觉对数据库整体编程的操作多了一类方法方案,拓宽了对于数据库编程的眼界。受益匪浅。其实我实际感觉数据库编程不管是之前学习的基础编程还是本学期学习的上一节的存储过程以及这节的触发器,编程都是存在共性,可以举一反三,通过多次实践,对数据库的理解也不断的加深。