0

我有这个触发器,它接近我想要完成的任务,但在尝试之后我仍然无法完成。

我做了什么

CREATE or REPLACE TRIGGER TR_UPD_TEST_TABLE_B
  AFTER INSERT ON TEST_TABLE_A
  FOR EACH ROW
DECLARE

BEGIN

  FOR VAL IN (SELECT * FROM TEST_TABLE_B A WHERE A.ID = :NEW.ID) LOOP
    IF :NEW.QTY_RECEIVED > VAL.QTY_PRE_RECEIVED THEN
      UPDATE TEST_TABLE_B A SET A.QTY_RECEIVED = 888 WHERE A.ID = :NEW.ID;
    ELSE
      UPDATE TEST_TABLE_B A SET A.QTY_RECEIVED = 111 WHERE A.ID = :NEW.ID;
    END IF;

  END LOOP;

END;

问题

通过使用IF :NEW.QTY_RECEIVED > VAL.QTY_PRE_RECEIVED,我想将 :NEW.QTY_RECEIVED 与每条记录进行比较,但似乎它总计了所有记录的数量。因此语句总是跳到 ,ELSE因为总量大于:NEW.QTY_RECEIVED

4

2 回答 2

0

你不需要循环。只需使用单个更新和案例即可。

CREATE or REPLACE TRIGGER TR_UPD_TEST_TABLE_B
  AFTER INSERT ON TEST_TABLE_A
  FOR EACH ROW
DECLARE

BEGIN
      UPDATE TEST_TABLE_B A SET A.QTY_RECEIVED = 
      case when :NEW.QTY_RECEIVED > QTY_PRE_RECEIVED then 888 else 111 end
      WHERE A.ID = :NEW.ID ;

END;
于 2013-09-10T10:34:19.180 回答
0

这是我终于出来的答案。

CREATE or REPLACE TRIGGER TR_UPD_TEST_TABLE_B
  AFTER INSERT ON TEST_TABLE_A
  FOR EACH ROW
DECLARE
  BALQTY NUMBER;
BEGIN
  BALQTY := :NEW.QTY_RECEIVED;
  FOR VAL IN (SELECT A.*
                FROM TEST_TABLE_B A
               WHERE A.ID = :NEW.ID
               ORDER BY A.ID1) LOOP

    IF BALQTY >= VAL.QTY_PRE_RECEIVED THEN
      UPDATE TEST_TABLE_B A
         SET A.QTY_RECEIVED     = A.QTY_RECEIVED + VAL.QTY_PRE_RECEIVED,
             A.QTY_PRE_RECEIVED = 0
       WHERE A.ID1 = VAL.ID1
         AND VAL.QTY_PRE_RECEIVED <> 0;
      BALQTY := BALQTY - VAL.QTY_PRE_RECEIVED;
    ELSIF BALQTY < VAL.QTY_PRE_RECEIVED AND BALQTY <> 0 AND BALQTY > 0 THEN
      UPDATE TEST_TABLE_B A
         SET A.QTY_RECEIVED     = A.QTY_RECEIVED + BALQTY,
             A.QTY_PRE_RECEIVED = VAL.QTY_PRE_RECEIVED - BALQTY
       WHERE A.ID1 = VAL.ID1
         AND VAL.QTY_PRE_RECEIVED <> 0;
      BALQTY := 0;
    ELSIF BALQTY = 0 THEN
      EXIT;
    END IF;

  END LOOP;

END;
于 2013-09-11T06:16:24.383 回答