Andrei
Andrei

Reputation: 51

"If" in a trigger comparing two columns from 2 different tables- error

Im trying to create a trigger when updating table 'test' to make sure a value in a column is not greater than another one from a different table. But I get this error on Oracle Apex: ORA-24344: success with compilation error

'test' is a table and 'chestionar' is a second one, so I want to launch that error when I insert a value in 'punctaj' which is greater than the 'punctaj_max'. And the id of the both tables must be the same . What should I modify?

here is my code:

CREATE OR REPLACE trigger trg_a
BEFORE UPDATE on test 
begin
if test.punctaj > chestionar.punctaj_max and test.id=chestionar.id then 
 raise_application_error(234,'error, the value is grater than maximum of that id');
end if;
end;

Upvotes: 0

Views: 684

Answers (2)

Popeye
Popeye

Reputation: 35910

You have three (I think) issue in your code:

  • You should apply trigger at time of insert also.
  • you need to query the table chestionar and then compare the value.
  • the error number in raise_application_error should be negative and between -20999 and -20000.

So, I would rewrite your code as follows:

create or replace trigger trg_a
before update or insert on test
for each row
declare 
    lv_cnt number := 0;
begin
    select count(1) into lv_cnt 
      from chestionar c 
     where c.id = :new.id
       and :new.punctaj > c.punctaj_max;

    if lv_cnt > 0 then 
        raise_application_error(-20234, 'error, the value is grater than maximum of that id');
    end if;
end;
/

Upvotes: 0

GMB
GMB

Reputation: 222512

I think the logic you want is:

create or replace trigger trg_a
before update on test
for each row
declare 
    p_punctaj_max chestionar.punctaj_max%type;
begin
    select punctaj_max into p_punctaj_max from chestionar c where c.id = :new.id;
    if :new.punctaj > p_punctaj_max then 
        raise_application_error(234, 'error, the value is grater than maximum of that id');
    end if;
end;
/

The idea is to recover the value of punctaj_max in table chestionar for the id of the row that is being updated in test (note that this implicitely assumes that there cannot be multiple matching rows in chestionar). We can then compare that to the value being updated, and raise the error if needed.

Upvotes: 0

Related Questions