CREATE OR REPLACE TRIGGER DTULTATU_CONFTELA
BEFORE INSERT OR UPDATE OR DELETE
ON CONFTELA FOR EACH ROW
DECLARE
   V_NRCONFTELA VARCHAR2(05);
   V_CDFILIAL VARCHAR2(04);
   V_DTINIVIGENCIA VARCHAR2(10);
   V_COUNT NUMBER;
   V_DSCHAVE VARCHAR2(100);
BEGIN
   IF INSERTING OR UPDATING THEN
      :NEW.DTULTATUCFTE := SYSDATE;
      V_NRCONFTELA := NVL(:NEW.NRCONFTELA, :OLD.NRCONFTELA);
      V_CDFILIAL := NVL(:NEW.CDFILIAL, :OLD.CDFILIAL);
      V_DTINIVIGENCIA := TO_CHAR(NVL(:NEW.DTINIVIGENCIA, :OLD.DTINIVIGENCIA), 'DD/MM/YYYY');
      V_DSCHAVE := V_CDFILIAL||'|'||V_NRCONFTELA||'|'||V_DTINIVIGENCIA;
      V_COUNT := 0;
      BEGIN
         SELECT COUNT(*)
           INTO V_COUNT
           FROM CTRLATUALTAB
          WHERE NMTABELA = 'CONFTELA'
            AND DSCHAVE = V_DSCHAVE;
      EXCEPTION
         WHEN NO_DATA_FOUND THEN
            V_COUNT := 0;
      END;
      IF V_COUNT = 0 THEN
         INSERT INTO CTRLATUALTAB
            (NMTABELA, DSCHAVE, DTULTATU)
         VALUES
            ('CONFTELA', V_DSCHAVE, SYSDATE);
      ELSE
         UPDATE CTRLATUALTAB
            SET DTULTATU = SYSDATE
          WHERE NMTABELA = 'CONFTELA'
            AND DSCHAVE = V_DSCHAVE;
      END IF;
   END IF;
   IF DELETING THEN
      INSERT INTO DELETECACHE (NMTABLECACHE, CDFILICACHE, DSKEYCACHE, DTULTATUCACH)
                       VALUES ('CONFTELA',:OLD.CDFILIAL, 'CDFILIAL='||:OLD.CDFILIAL||';NRCONFTELA='||:OLD.NRCONFTELA||';', SYSDATE);
   END IF;
END;
/

ALTER TABLE CONFTELA MODIFY DTULTATUCFTE DEFAULT SYSDATE
/

UPDATE CONFTELA SET DTULTATUCFTE = SYSDATE WHERE DTULTATUCFTE IS NULL
/

-- VERSAO --
BEGIN ATUVEROBJ('DTULTATU_CONFTELA','6.35.041'); END;
/

