0

次のトリガーを実装する必要があります。

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;
4

2 に答える 2

2

投票数の合計が複数の行から決定されるため、選挙テーブルにクエリを実行する必要があることが問題であると仮定すると、「行ごとに」を削除してステートメントレベルのトリガーにすると(クエリを変更して確認する必要があります)どの行が挿入/更新されたかわからないため、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'
于 2016-01-14T19:16:43.293 に答える
1

そこにトリガーが必要ですか?チェック制約を使用してこの問題を解決できます。

alter table election add consntraint too_many_votes check (votes < 538 or year < 1960);
于 2016-01-14T18:53:54.603 に答える