oracle触发器中的子查询

时间:2018-08-21 05:33:59

标签: oracle database-trigger

我想基于表中的数据在触发器中包含条件。由于oracle确实允许触发器中的子查询,因此如何实现它。请在下面找到我的代码。 Trans_code_master包含有效代码列表,可以更改。

预先感谢您的帮助。

CREATE OR REPLACE TRIGGER CUST_TRG
BEFORE INSERT OR UPDATE ON CUST_ALL_TRANS
REFERENCING OLD AS OLD NEW AS NEW
FOR EACH ROW
WHEN (NEW.TRANSACTION_CODE IN(SELECT TRANS_CODE FROM TRANS_CODE_MASTER))
BEGIN

  INSERT INTO CUST_DEPO_TRANS
  (
   CUST_ID
  ,AC_ID
  ,TRANSACTION_CODE
  )
  VALUES(
   :NEW.CUST_ID
  ,:NEW.AC_ID
  ,:NEW.TRANSACTION_CODE
  )
EXCEPTION
   WHEN OTHERS THEN
     -- Consider logging the error and then re-raise
     RAISE;
END;
/

1 个答案:

答案 0 :(得分:1)

在when子句中的写查询中是不可能的。请尝试以下方式

CREATE OR REPLACE TRIGGER CUST_TRG
BEFORE INSERT OR UPDATE ON CUST_ALL_TRANS
REFERENCING OLD AS OLD NEW AS NEW
FOR EACH ROW
DECLARE
     V_CNT NUMBER;
BEGIN
  SELECT COUNT(1) INTO V_CNT
  FROM TRANS_CODE_MASTER 
  WHERE TRANS_CODE = NEW.TRANSACTION_CODE;
  IF V_CNT > 0 THEN
  INSERT INTO CUST_DEPO_TRANS
  (
   CUST_ID
  ,AC_ID
  ,TRANSACTION_CODE
  )
  VALUES(
   :NEW.CUST_ID
  ,:NEW.AC_ID
  ,:NEW.TRANSACTION_CODE
  )
  END IF;
EXCEPTION
   WHEN OTHERS THEN
     -- Consider logging the error and then re-raise
     RAISE;
END;
/