create or replace TRIGGER OU_REF.INSTITUTION_ROLE_H
BEFORE INSERT OR UPDATE OR DELETE ON OU_REF.INSTITUTION_ROLE
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 DW_REF_MAIN.INSTITUTION_ROLE(ROLE_CODE, ROLE_DESCRIPTION, A_VALID_FROM, A_VALID_TO, A_KEY)
    VALUES (:new.ROLE_CODE, :new.ROLE_DESCRIPTION, v_current_date, v_future_date, NULL);
    INSERT INTO DW_REF_MAIN.INSTITUTION_ROLE_C2D(ROLE_CODE, ROLE_DESCRIPTION, A_VALID_FROM, A_VALID_TO, A_KEY)
    VALUES (:new.ROLE_CODE, :new.ROLE_DESCRIPTION, v_current_date, v_future_date, NULL);
  ELSIF DELETING THEN
    UPDATE DW_REF_MAIN.INSTITUTION_ROLE SET
      A_VALID_TO = v_current_date
    WHERE  
        1 = 1 
    AND DECODE(ROLE_CODE, :old.ROLE_CODE, 1, 0) = 1
    AND DECODE(ROLE_DESCRIPTION, :old.ROLE_DESCRIPTION, 1, 0) = 1
    AND A_VALID_TO = v_future_date
  ;
  UPDATE DW_REF_MAIN.INSTITUTION_ROLE_C2D SET
      A_VALID_TO = v_current_date
    WHERE  
        1 = 1 
    AND DECODE(ROLE_CODE, :old.ROLE_CODE, 1, 0) = 1
    AND DECODE(ROLE_DESCRIPTION, :old.ROLE_DESCRIPTION, 1, 0) = 1
    AND A_VALID_TO = v_future_date
  ;
  ELSIF UPDATING THEN
    UPDATE DW_REF_MAIN.INSTITUTION_ROLE SET
      A_VALID_TO = v_current_date
    WHERE  
        1 = 1 
    AND DECODE(ROLE_CODE, :old.ROLE_CODE, 1, 0) = 1
    AND DECODE(ROLE_DESCRIPTION, :old.ROLE_DESCRIPTION, 1, 0) = 1
    AND A_VALID_TO = v_future_date
  ;
  UPDATE DW_REF_MAIN.INSTITUTION_ROLE_C2D SET
      A_VALID_TO = v_current_date
    WHERE  
        1 = 1 
    AND DECODE(ROLE_CODE, :old.ROLE_CODE, 1, 0) = 1
    AND DECODE(ROLE_DESCRIPTION, :old.ROLE_DESCRIPTION, 1, 0) = 1
    AND A_VALID_TO = v_future_date
  ;
    INSERT INTO DW_REF_MAIN.INSTITUTION_ROLE(ROLE_CODE, ROLE_DESCRIPTION, A_VALID_FROM, A_VALID_TO, A_KEY)
    VALUES (:new.ROLE_CODE, :new.ROLE_DESCRIPTION, v_current_date, v_future_date, NULL);
    INSERT INTO DW_REF_MAIN.INSTITUTION_ROLE_C2D(ROLE_CODE, ROLE_DESCRIPTION, A_VALID_FROM, A_VALID_TO, A_KEY)
    VALUES (:new.ROLE_CODE, :new.ROLE_DESCRIPTION, v_current_date, v_future_date, NULL);
  END IF;
END;
/