我有2个触发器。另外,每个触发器都可以工作但不能在一起工作。
错误:消息16915,级别16,状态1,程序PrumerAsistence,第16行 一个名为' curff'的游标。已经存在。 该语句已终止。
TRIGGER 1:
create trigger PrumerAsistence on Hrac FOR UPDATE as
BEGIN
declare @old DATE
declare @new date
declare @YearOld int
declare @YearNew int
declare @Year int
declare @Asistence float
declare @id int
declare @as float
declare curff cursor for (
select inserted.hid
from inserted
)
open curff
fetch from curff into @id
while @@fetch_status = 0
BEGIN
set @old = (select min(datum)from prestup where @id = prestup.Hrac_hid)
set @new = (select max (datum) from prestup where @id = prestup.Hrac_hid)
set @YearOld = (select Year(@old))
set @YearNew = (select Year(@new))
set @Year = @YearNew- @YearOld
set @as = (
select sum (Asistence)/ @Year
from hrac
join prestup p on p.hrac_hid = hrac.hid
where hid = @id )
update Hrac set Prumer_Asistence = @as where hid = @id
fetch from curff into @id
END
close curff
deallocate curff
TRIGGER 2:
create trigger PrumerGolu on Hrac for UPDATE as
BEGIN
declare @old DATE
declare @new date
declare @YearOld int
declare @YearNew int
declare @Year int
declare @Gol float
declare @id int
declare @as float
declare cur cursor for (
select inserted.hid
from inserted
)
open cur
fetch from cur into @id
while @@fetch_status = 0
BEGIN
set @old = (select min(datum)from prestup where @id = prestup.Hrac_hid)
set @new = (select max (datum) from prestup where @id = prestup.Hrac_hid)
set @YearOld = (select Year(@old))
set @YearNew = (select Year(@new))
set @Year = @YearNew- @YearOld
set @gol = (
select sum (gol)/ @Year
from hrac
join prestup p on p.hrac_hid = hrac.hid
where hid = @id )
update Hrac set Prumer_Golu = @gol where hid = @id
fetch from cur into @id
END
close cur
deallocate cur
答案 0 :(得分:0)
您不应该为两个不同的表光标使用相同的名称,因为它们同时发生。
更重要:
由于调整活动,建议不要在您的情况下使用光标。 @@fetch_status
是一个全局变量,是所有会话和所有批次的范围。它可能会导致冲突并使结果不准确。
最好将这两个触发器组合在一起,让SQL执行器考虑首先需要处理哪个游标,否则可能会导致数据丢失等。
答案 1 :(得分:0)
确保使用LOCAL选项声明每个光标。
有关如何执行此操作的详细信息,请参阅此处,以及有关如何检查默认设置的信息(我猜测GLOBAL)。
https://technet.microsoft.com/en-us/library/ms189238(v=sql.105).aspx
答案 2 :(得分:0)
这是我上学的项目,我必须使用2触发器。我知道为什么,但我必须。
不能使用Local。 Msg 217,Level 16,State 1,Procedure PrumerGolu,Line 38 超出了最大存储过程,函数,触发器或视图嵌套级别(限制32)。