create or replace TRIGGER OU_REF.CSDB_RATING_ACTION_H
BEFORE INSERT OR UPDATE OR DELETE ON OU_REF.CSDB_RATING_ACTION
REFERENCING NEW AS new OLD AS old
FOR EACH ROW
DECLARE
  v_current_date DATE := SYSDATE;
  v_future_date DATE  := TO_DATE('31/12/9999', 'DD/MM/YYYY');
BEGIN
  IF INSERTING THEN
    INSERT INTO REFERENCE.T_CSDB_RATING_ACTION(CSDB_RATING_ACTION_CODE, CSDB_RATING_ACTION_DESC, SOURCE, A_VALID_FROM, A_VALID_TO, A_KEY, A_MOPDB_LOAD_SET_FK)
    VALUES (:new.CSDB_RATING_ACTION_CODE, :new.CSDB_RATING_ACTION_DESC, :new.SOURCE, v_current_date, v_future_date, NULL, -1);
  ELSIF DELETING THEN
    UPDATE REFERENCE.T_CSDB_RATING_ACTION SET
      A_VALID_TO = v_current_date
    WHERE  
        1 = 1 
    AND DECODE(CSDB_RATING_ACTION_CODE, :old.CSDB_RATING_ACTION_CODE, 1, 0) = 1
    AND DECODE(CSDB_RATING_ACTION_DESC, :old.CSDB_RATING_ACTION_DESC, 1, 0) = 1
    AND DECODE(SOURCE, :old.SOURCE, 1, 0) = 1
    AND A_VALID_TO = v_future_date
  ;
  ELSIF UPDATING THEN
    UPDATE REFERENCE.T_CSDB_RATING_ACTION SET
      A_VALID_TO = v_current_date
    WHERE  
        1 = 1 
    AND DECODE(CSDB_RATING_ACTION_CODE, :old.CSDB_RATING_ACTION_CODE, 1, 0) = 1
    AND DECODE(CSDB_RATING_ACTION_DESC, :old.CSDB_RATING_ACTION_DESC, 1, 0) = 1
    AND DECODE(SOURCE, :old.SOURCE, 1, 0) = 1
    AND A_VALID_TO = v_future_date
  ;
    INSERT INTO REFERENCE.T_CSDB_RATING_ACTION(CSDB_RATING_ACTION_CODE, CSDB_RATING_ACTION_DESC, SOURCE, A_VALID_FROM, A_VALID_TO, A_KEY, A_MOPDB_LOAD_SET_FK)
    VALUES (:new.CSDB_RATING_ACTION_CODE, :new.CSDB_RATING_ACTION_DESC, :new.SOURCE, v_current_date, v_future_date, NULL, -1);
  END IF;
END;
/