'trigger to calculate the max possible value of a column before insert or update

i have 2 tables : parent and child, there is a certain column in the parent table defining max_bill_value, and a column in child table defining bill_value. the condition here is :

sum(bill_value)<max_bill_value 

the trigger body should be something like this

CREATE OR REPLACE TRIGGER check_max_value
BEFORE INSERT ON child_table
FOR EACH ROW
  sum_bill_value number;
  max_bill_value number; 
BEGIN
SELECT bill_value INTO max_bill_value FROM parent_table WHERE id=:NEW.parent_id; 

SELECT SUM(bill_value) INTO sum_bill_value FROM child_table where parent_id=:NEW.parent_id; 

if max_bill_value < sum_bill_value then raise_application_error(-20001, 'ERROR!!!');
end if;
END;
/

my first solution was the use of a trigger, which was impossible because of the

"ORA-04091: table name is mutating, trigger/function may not see it." message. my second solution was the use of a table level trigger by removing FOR EACH ROW , which made me unable to reference :NEW or :OLD.

so what would be a simple solution for this?

sql


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source