如果 tableB.columnZ 表示被引用的 tableA 记录的计数,那么除非 tableA 的引用列可以更改,否则触发 tableA 的 UPDATE 是没有意义的。
第一种情况:tableA.ReferenceColumn 不变:
CREATE OR REPLACE TRIGGER test_trig
AFTER INSERT ON tableA
FOR EACH ROW
BEGIN
UPDATE tableB
SET columnZ = columnZ + 1
WHERE tableB.columnX = :NEW.columnX;
END test_trig;
/
第二种情况:tableA.ReferenceColumn 确实发生了变化:
CREATE OR REPLACE TRIGGER test_trig
AFTER INSERT OR UPDATE OF columnX ON tableA
FOR EACH ROW
BEGIN
IF UPDATING AND nvl(:OLD.columnX,0) <> 0 THEN
UPDATE tableB
SET columnZ = columnZ - 1
WHERE tableB.columnX = :OLD.columnX;
END IF:
IF nvl(:NEW.columnX,0) <> 0 THEN
UPDATE tableB
SET columnZ = columnZ + 1
WHERE tableB.columnX = :NEW.columnX;
END IF;
END test_trig;
/
第三种情况:tablaA 记录可以被删除:
CREATE OR REPLACE TRIGGER test_trig
AFTER INSERT OR DELETE OR UPDATE OF columnX ON tableA
FOR EACH ROW
BEGIN
IF (UPDATING OR DELETING) AND nvl(:OLD.columnX,0) <> 0 THEN
UPDATE tableB
SET columnZ = columnZ - 1
WHERE tableB.columnX = :OLD.columnX;
END IF:
IF nvl(:NEW.columnX,0) <> 0 THEN
UPDATE tableB
SET columnZ = columnZ + 1
WHERE tableB.columnX = :NEW.columnX;
END IF;
END test_trig;
/