码迷,mamicode.com
首页 > 其他好文 > 详细

以学生表实例来补充 触发器和游标操作

时间:2017-05-04 11:08:15      阅读:200      评论:0      收藏:0      [点我收藏+]

标签:触发器   eal   font   val   select   ges   测试   test   sts   

这是学生表里面的内容:

技术分享

 

现在创建一个Avgtable表:

select Sno, AVG(Grade) avgGrade into Avgtable from SC
group by Sno

--情况是这样子的:
--当向SC表中做插入操作的时候,插入数据的时候 Avgtable表是要改变数据的:
-- 1.当插入Avgtable表中目前没有的学生的数据的时候就直接插入
-- 2.当插入Avgtable表中已经有的学生的数据的时候就要求要改变avgGrade的值
--触发器做插入的时候:

alter trigger tri_Test on SC for insert,delete
as 
if not exists(select * from Avgtable, inserted where Avgtable.Sno = inserted.Sno)
insert into Avgtable select Sno, Grade from inserted
else
begin
declare @Sno varchar(7)
select @Sno = Sno from inserted
update Avgtable
set avgGrade = (select AVG(Grade) from SC where Sno = @Sno)
where Sno = @Sno
end

 


--测试:
insert into SC values (‘2017001‘,‘2‘,88)


--当插入多条记录的时候:
insert into SC values
(‘2017004‘, ‘1‘, 90),
(‘2017004‘, ‘2‘, 80),
(‘2017004‘, ‘3‘, 40)

技术分享

为什么会出现错误?
是因为当插入多条纪录的时候 触发器 中 inserted 表中会有三条记录
if not exists(select * from Avgtable, inserted where Avgtable.Sno = inserted.Sno)
这个条件刚好成立 然后就进入了 insert into Avgtable select Sno, Grade from inserted
将会把inserted表中的三条纪录全部插入到Avgtable表中。

解决办法就是使用游标:
--创建触发器(使用游标):

alter trigger tri_OnSC on SC for insert
as 
declare culInsert cursor for select Sno,Cno,Grade from SC
open culInsert
declare @Sno varchar(7), @Cno char(1), @Grade int 
fetch next from culInsert into @Sno, @Cno, @Grade
while @@FETCH_STATUS = 0
begin 
if not exists(select * from Avgtable where Sno = @Sno)
insert into Avgtable values(@Sno, @Grade)
else
update Avgtable
set avgGrade = (select AVG(Grade) from SC where Sno = @Sno)
where Sno = @Sno
fetch next from culInsert into @Sno, @Cno, @Grade
end
close culInsert
deallocate culInsert

 

以学生表实例来补充 触发器和游标操作

标签:触发器   eal   font   val   select   ges   测试   test   sts   

原文地址:http://www.cnblogs.com/yangfan-123/p/6805679.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!