create or replace TRIGGER OU_REF.BALANCE_SHEET_STRUCTURE_H
BEFORE INSERT OR UPDATE OR DELETE ON OU_REF.BALANCE_SHEET_STRUCTURE
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_BALANCE_SHEET_STRUCTURE(ISIS_CODE, BS_ITEM_CODE, DESCRIPTION, BS_SUB_ITEM, BS_ITEM, BS_ITEM_GROUP, BS_ITEM_TYPE, A_VALID_FROM, A_VALID_TO, A_KEY, A_MOPDB_LOAD_SET_FK)
    VALUES (:new.ISIS_CODE, :new.BS_ITEM_CODE, :new.DESCRIPTION, :new.BS_SUB_ITEM, :new.BS_ITEM, :new.BS_ITEM_GROUP, :new.BS_ITEM_TYPE, v_current_date, v_future_date, NULL, -1);
  ELSIF DELETING THEN
    UPDATE REFERENCE.T_BALANCE_SHEET_STRUCTURE SET
      A_VALID_TO = v_current_date
    WHERE  
        1 = 1 
    AND DECODE(ISIS_CODE, :old.ISIS_CODE, 1, 0) = 1
    AND DECODE(BS_ITEM_CODE, :old.BS_ITEM_CODE, 1, 0) = 1
    AND DECODE(DESCRIPTION, :old.DESCRIPTION, 1, 0) = 1
    AND DECODE(BS_SUB_ITEM, :old.BS_SUB_ITEM, 1, 0) = 1
    AND DECODE(BS_ITEM, :old.BS_ITEM, 1, 0) = 1
    AND DECODE(BS_ITEM_GROUP, :old.BS_ITEM_GROUP, 1, 0) = 1
    AND DECODE(BS_ITEM_TYPE, :old.BS_ITEM_TYPE, 1, 0) = 1
    AND A_VALID_TO = v_future_date
  ;
  ELSIF UPDATING THEN
    UPDATE REFERENCE.T_BALANCE_SHEET_STRUCTURE SET
      A_VALID_TO = v_current_date
    WHERE  
        1 = 1 
    AND DECODE(ISIS_CODE, :old.ISIS_CODE, 1, 0) = 1
    AND DECODE(BS_ITEM_CODE, :old.BS_ITEM_CODE, 1, 0) = 1
    AND DECODE(DESCRIPTION, :old.DESCRIPTION, 1, 0) = 1
    AND DECODE(BS_SUB_ITEM, :old.BS_SUB_ITEM, 1, 0) = 1
    AND DECODE(BS_ITEM, :old.BS_ITEM, 1, 0) = 1
    AND DECODE(BS_ITEM_GROUP, :old.BS_ITEM_GROUP, 1, 0) = 1
    AND DECODE(BS_ITEM_TYPE, :old.BS_ITEM_TYPE, 1, 0) = 1
    AND A_VALID_TO = v_future_date
  ;
    INSERT INTO REFERENCE.T_BALANCE_SHEET_STRUCTURE(ISIS_CODE, BS_ITEM_CODE, DESCRIPTION, BS_SUB_ITEM, BS_ITEM, BS_ITEM_GROUP, BS_ITEM_TYPE, A_VALID_FROM, A_VALID_TO, A_KEY, A_MOPDB_LOAD_SET_FK)
    VALUES (:new.ISIS_CODE, :new.BS_ITEM_CODE, :new.DESCRIPTION, :new.BS_SUB_ITEM, :new.BS_ITEM, :new.BS_ITEM_GROUP, :new.BS_ITEM_TYPE, v_current_date, v_future_date, NULL, -1);
  END IF;
END;
/