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