Oracle:触发器无法正常工作

时间:2015-10-20 10:01:10

标签: sql oracle plsql database-trigger

我有这个触发器:

CREATE OR REPLACE TRIGGER trig_update_process_info
  AFTER INSERT ON rocessstep FOR EACH ROW
DECLARE
  audit_time TIMESTAMP(6);
  found_flag NUMBER DEFAULT 0;
BEGIN

  SELECT MAX(lastupdatetime) INTO audit_time
    FROM processinfo
   WHERE instance = :new.instance;

EXCEPTION
  WHEN no_data_found THEN
    found_flag := NULL;

    IF found_flag IS NULL
    THEN
      INSERT INTO processinfo
       VALUES (:new.instance, :new.step, :new.status, :new.iteration, :new.audittime);
    ELSE
      IF :new.audittime > audit_time
      THEN
        UPDATE processinfo
        SET step = :new.step, lastupdatetime = :new.audittime, status = :new.status, iteration = :new.iteration
        WHERE instance = :new.instance;
      END IF;
    END IF;
END;

但它不起作用。你能告诉我这个触发器有什么问题吗?

这是目标表:

CREATE TABLE PROCESSINFO(
    INSTANCE   CHAR(36 BYTE) NOT NULL, 
    STEP       VARCHAR2(128 BYTE) NOT NULL, 
    STATUS     NUMBER(*,0) NOT NULL,
    ITERATION  NUMBER(*,0) NOT NULL,
    LASTUPDATETIME TIMESTAMP(6) NOT NULL
);

由于

1 个答案:

答案 0 :(得分:1)

由于汇总,您的查询永远不会抛出no_data_found。相反,如果没有匹配的数据,那么audit_time将为空,因此您可以测试它 - 完全不需要found_flag。并且如同编写的那样,整个if / else部分都在异常处理程序中,因此永远无法对其进行评估(如果没有抛出异常,大概你会期望击中else部分,但是你没有在查询周围分开开始/结束,因此您无法正确构建块。

...
BEGIN
  SELECT MAX(LASTUPDATETIME) INTO AUDIT_TIME FROM PROCESSINFO
  WHERE INSTANCE = :NEW.INSTANCE;

  IF AUDIT_TIME IS NULL 
  THEN
    INSERT INTO PROCESSINFO (INSTANCE, STEP, STATUS, ITERATION, LASTUPDATETIME)
      VALUES (:NEW.INSTANCE, :NEW.STEP, :NEW.STATUS, :NEW.ITERATION, :NEW.AUDITTIME);
  ELIF :NEW.AUDITTIME > AUDIT_TIME THEN 
    UPDATE PROCESSINFO SET STEP = :NEW.STEP, LASTUPDATETIME = :NEW.AUDITTIME,
      STATUS = :NEW.STATUS, ITERATION = :NEW.ITERATION
    WHERE INSTANCE = :NEW.INSTANCE;
  END IF;
END;

看起来每个processinfo只能在instance中有一行,所以你也可以考虑合并语句,而不是选择是否更新或插入。

ON ROCESSSTEP看起来很奇怪,但如果该表名错误,则根本不会创建触发器,而不仅仅是“不工作”。