【发布时间】:2016-04-20 05:27:42
【问题描述】:
我必须实现以下触发器:
1960 年之后的选举,每个选举年的总票数不超过 538
但是,我得到了变异表错误。我明白为什么我会收到错误消息,但我看不到其他解决方案(带触发器)。我可以创建一个临时表,但我只想拥有触发器。 代码如下:
CREATE OR REPLACE TRIGGER restrict_election_votes
after INSERT OR UPDATE ON election
for each row
declare
v_nbofvotes number;
v_eleyr election.election_year%type :=:NEW.election_year;
v_votes election.votes%type :=:NEW.VOTES;
begin
select sum(votes)
into v_nbofvotes
from election
where election_year=v_eleyr;
if(v_votes+v_nbofvotes >538)
THEN
RAISE_APPLICATION_ERROR(-20500, 'Too many votes');
END IF;
END;
update election
set votes=175
where candidate='MCCAIN J'
and election_year=2008;
【问题讨论】:
-
如果您删除“for each row”并使其成为语句级触发器(将不得不更改查询以检查自 1960 年以来所有选举的 sum(votes) 规则,因为您不知道插入/更新了哪一行)那么它应该可以工作。
-
我认为这里的问题不是“每一行”而是从自身中选择。只需删除 select 语句,我认为您实际上并不需要它:您只需要检查 :NEW.VOTES 。
-
CREATE OR REPLACE TRIGGER restrict_election_votes before INSERT OR UPDATE ON election declare v_nbofvotes number; begin select sum(votes) into v_nbofvotes from election where election_year>1960; if(v_nbofvotes >(538 *((extract( year from sysdate))-1960))) THEN RAISE_APPLICATION_ERROR(-20500, 'Too many votes'); END IF; END;还是不行 -
@stee1rat - 我的印象是,限制是选举的总票数,而不是候选人,这意味着必须查询选举中的所有候选人。]
-
@MonicaS - 我将其充实到下面的答案中以证明我的意思。
标签: sql oracle plsql triggers mutating-table