简体   繁体   中英

Oracle Before Update Trigger

I want to write a trigger that checks my table and if condition satisfied then makes an update the table. To be more specific, I have two tables: firs,

CELL(CellId, x0, y0, x1, y1, CurrentPhone#, MaxCalls)
TELEPHONE(PhoneNo, x, y, PhoneState)

And I have a query like:

UPDATE CELL SET MaxCalls = MaxCalls-5;

And my trigger should check sum of all MaxCalls in the CELL table, and it will be always greater than 30. If in some moment, before new value of MaxCalls updated, MaxCalls sum get lower than 30 the trigger should write an error message and stop updating.

Here is my trigger, but it gives me errors.

CREATE OR REPLACE TRIGGER Change_Max_Calls
BEFORE UPDATE ON CELL 
FOR EACH ROW
DECLARE
  SUMMA INTEGER;
  CurrentCalls INTEGER;
  cx0 INTEGER; cx1 INTEGER; cy0 INTEGER; cy1 INTEGER;
BEGIN
SELECT SUM(MaxCalls) INTO SUMMA FROM CELL;
    IF (SUMMA-:NEW.MaxCalls)<30 THEN
      DBMS_OUTPUT.PUT_LINE('The sum of MaxCalls should be greater than or equal to 30');
    ELSE
      cx0 := :OLD.x0;
      cx1 := :OLD.x1;
      cy0 := :OLD.y0;
      cy1 := :OLD.y1;
        SELECT COUNT(*) INTO CurrentCalls FROM TELEPHONE
        WHERE PhoneState='Active' AND x>=cx0 AND x<cx1 AND y>=cy0 AND y<cy1;
        IF :new.MaxCalls<CurrentCalls THEN 
          :new.MaxCalls := CurrentCalls; 
        END IF;  
    END IF;


END;

This part of trigger working well, because I have checked it before:

cx0 := :OLD.x0;
      cx1 := :OLD.x1;
      cy0 := :OLD.y0;
      cy1 := :OLD.y1;
        SELECT COUNT(*) INTO CurrentCalls FROM TELEPHONE
        WHERE PhoneState='Active' AND x>=cx0 AND x<cx1 AND y>=cy0 AND y<cy1;
        IF :new.MaxCalls<CurrentCalls THEN 
          :new.MaxCalls := CurrentCalls; 
        END IF; 

Please, help me with this problem. Thank you!

To resolve your mutating trigger problem, you should use a compound trigger, where you make the selects in the before statement, and perform the changes in the before each row statement:

http://viralpatel.net/blogs/compound-triggers-in-oracle-11g-tutorial-example/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM