CREATE OR REPLACE TRIGGER LOG_CONTCTBL
BEFORE UPDATE OR INSERT OR DELETE ON CONTCTBL
FOR EACH ROW
DECLARE
   V_USUARIO VARCHAR2(40);
   V_TIPO VARCHAR2(1);
   V_DESC VARCHAR2(300);
   V_DSREMOTEADDR VARCHAR2(15);
   V_DSREMOTEHOST VARCHAR2(15);
   V_DSSERVERRDM  VARCHAR2(20);
   V_DSSERVMETHOD VARCHAR2(30);
   V_DSREMOTEOPER VARCHAR2(12);
   V_CONTA VARCHAR2(20);
BEGIN
   V_DESC := '';
   IF INSERTING THEN
      V_CONTA := :NEW.CDCONTCTBL;
      :NEW.DTULTATUCCTB := SYSDATE;
      V_TIPO := '1';
      V_DESC := 'CONTA: '||:NEW.CDCONTCTBL||' NOME: '||:NEW.NMCONTCTBL||' IDCONTCCUS: '||:NEW.IDCONTCCUS||' IDTIPOCOME: '||:NEW.IDTIPOCOME||' IDNATUCONT: '||:NEW.IDNATUCONT||' ';
      V_DESC := V_DESC||' CDCONTPLANREFE: '||:NEW.CDCONTPLANREFE||' CDCONTREFEAUX: '||:NEW.CDCONTREFEAUX||' CDCONTREFEPRE: '||:NEW.CDCONTREFEPRE;
   ELSIF UPDATING THEN
      :NEW.DTULTATUCCTB := SYSDATE;
      V_CONTA := :NEW.CDCONTCTBL;
      V_TIPO := '2';
      V_DESC := 'CONTA: '||:NEW.CDCONTCTBL||' NOME: '||:NEW.NMCONTCTBL||' IDCONTCCUS: '||:NEW.IDCONTCCUS||' IDTIPOCOME: '||:NEW.IDTIPOCOME||' IDNATUCONT: '||:NEW.IDNATUCONT||' ';
      V_DESC := V_DESC||' CDCONTPLANREFE: '||:NEW.CDCONTPLANREFE||' CDCONTREFEAUX: '||:NEW.CDCONTREFEAUX||' CDCONTREFEPRE: '||:NEW.CDCONTREFEPRE;
   ELSE
      V_CONTA := :OLD.CDCONTCTBL;
      V_TIPO := '3';
      V_DESC := 'CONTA: '||:OLD.CDCONTCTBL||' NOME: '||:OLD.NMCONTCTBL||' IDCONTCCUS: '||:OLD.IDCONTCCUS||' IDTIPOCOME: '||:OLD.IDTIPOCOME||' IDNATUCONT: '||:OLD.IDNATUCONT||' ';
      V_DESC := V_DESC||' CDCONTPLANREFE: '||:OLD.CDCONTPLANREFE||' CDCONTREFEAUX: '||:OLD.CDCONTREFEAUX||' CDCONTREFEPRE: '||:OLD.CDCONTREFEPRE;
   END IF;

   NMUSUARIO(V_USUARIO);
   WEBTUNNING(V_DSREMOTEADDR,
              V_DSREMOTEHOST,
              V_DSSERVERRDM,
              V_DSSERVMETHOD,
              V_DSREMOTEOPER);

   INSERT INTO LOGOPERA
      (NMTABELA,   DTOPERACAO, NMRESPOPER,
       IDTIPOOPER, CDPESQITEM, DSOPERACAO,
       DSRDMUSUOPER, DSENDUSUOPER, DSNMUSUOPER, DSMETUSUOPER, CDORESPOPER)
   VALUES
      ('CONTCTBL',  SYSDATE, V_USUARIO,
       V_TIPO, V_CONTA, V_DESC,
       V_DSSERVERRDM, V_DSREMOTEADDR, V_DSREMOTEHOST, V_DSSERVMETHOD, V_DSREMOTEOPER);
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('LOG_CONTCTBL','6.05.xxx'); END;
/

DECLARE
   V_COUNT NUMBER;
BEGIN
   V_COUNT := 0;
   BEGIN
      SELECT COUNT(*)
        INTO V_COUNT
        FROM LOGOPERA
       WHERE NMTABELA = 'CONTCTBL';
   EXCEPTION
      WHEN NO_DATA_FOUND THEN
         V_COUNT := 0;
   END;
   IF V_COUNT = 0 THEN
      /* UPDATE APENAS PARA GRAVAR OS DADOS INICIAIS DE LOG */
      UPDATE CONTCTBL
         SET CDRATEIO = CDRATEIO;
   END IF;
END;
/