Oracle更新前触发器

时间:2016-11-22 12:46:19

标签: sql oracle database-trigger

我想编写一个检查我的表的触发器,如果​​条件满足则更新表。更具体地说,我有两个表:冷杉,

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

我的查询如下:

UPDATE CELL SET MaxCalls = MaxCalls-5;

我的触发器应该检查CELL表中所有MaxCalls的总和,并且它总是大于30.如果在某个时刻,在更新MaxCalls的新值之前,MaxCalls总和低于30,则触发器应写入错误消息并停止更新。

这是我的触发器,但它给了我错误。

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;

这部分触发器运行良好,因为我之前已经检查过:

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; 

请帮我解决这个问题。谢谢!

1 个答案:

答案 0 :(得分:0)

要解决变异触发器问题,您应该使用复合触发器,在before语句中进行选择,并在每行语句之前执行更改:

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