CREATE OR REPLACE TRIGGER ATUALIZA_MESAF
BEFORE UPDATE OR INSERT
ON AUTOFORNE FOR EACH ROW
BEGIN
   IF INSERTING THEN
      :NEW.DTMESAUTOFOR := TRUNC(:NEW.DTAUTOFORN) - TO_NUMBER(TO_CHAR(:NEW.DTAUTOFORN, 'DD')) + 1;
   ELSE
      IF NVL(:OLD.DTAUTOFORN, TO_DATE('01/01/3500', 'DD/MM/YYYY')) <> NVL(:NEW.DTAUTOFORN, TO_DATE('01/01/3500', 'DD/MM/YYYY')) THEN
         :NEW.DTMESAUTOFOR := TRUNC(:NEW.DTAUTOFORN) - TO_NUMBER(TO_CHAR(:NEW.DTAUTOFORN, 'DD')) + 1;
      END IF;
   END IF;
END;
/

UPDATE
   AUTOFORNE SET DTMESAUTOFOR = TRUNC(DTAUTOFORN) - TO_CHAR(DTAUTOFORN, 'DD') + 1
WHERE
   DTMESAUTOFOR IS NULL
/

-- VERSAO --
BEGIN ATUVEROBJ('ATUALIZA_MESAF','4.05.111'); END;
/
