变异表 - 触发错误

时间:2016-01-14 18:34:19

标签: sql oracle plsql triggers mutating-table

我必须实现以下触发器:

  

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;

2 个答案:

答案 0 :(得分:2)

假设问题是您需要查询选举表,因为投票计数总数是从多行确定的,那么如果您删除“for each row”并使其成为语句级别触发器(将必须更改查询以检查自1960年以来所有选举的总和(投票)规则,因为您不知道插入/更新了哪一行)然后它将起作用。

create table mb_elct (year varchar2(4), cand varchar2(30), vt number)

create or replace trigger mb_elct_trg
after insert or update on mb_elct
declare 
   v_nbofvotes number;
begin
select count(*) 
into  v_nbofvotes
from (
  select year, sum(vt)
    from mb_elct
  where  year > '1960'
  group by year
  having sum(vt) >538
);

if(nvl(v_nbofvotes,0) != 0 ) 
THEN
    RAISE_APPLICATION_ERROR(-20500, 'Too many votes');
  END IF;

END;
/

insert into mb_elct values ('2008', 'McCain', 500);

1 row inserted

update mb_elct set vt = vt + 200 where year = '2008' and cand = 'McCain';
ORA-20500: Too many votes
ORA-06512: at "EDR_ADMIN.MB_ELCT_TRG", line 16
ORA-04088: error during execution of trigger 'EDR_ADMIN.MB_ELCT_TRG'

答案 1 :(得分:1)

你确定你需要一个触发器吗?您可以使用check constraint

解决此问题
alter table election add consntraint too_many_votes check (votes < 538 or year < 1960);