IF EXISTS(SELECT * FROM sysobjects O, sysusers U
          WHERE
            o.name = 'ATUALIZA_MESAF'  and
            type = 'TR'                 and
            u.uid = o.uid               and
            u.name = USER)
  DROP TRIGGER ATUALIZA_MESAF
  GO

CREATE TRIGGER ATUALIZA_MESAF
ON AUTOFORNE
FOR INSERT, UPDATE
AS
BEGIN
  UPDATE AUTOFORNE
  SET
    DTMESAUTOFOR = AUTOFORNE.DTAUTOFORN - DAY(AUTOFORNE.DTAUTOFORN) + 1
  FROM
    INSERTED
  WHERE
    AUTOFORNE.CDFILDEST  = INSERTED.CDFILDEST AND
    AUTOFORNE.CDFILLANC  = INSERTED.CDFILLANC AND
    AUTOFORNE.NRAUTOFORN = INSERTED.NRAUTOFORN
END;
GO

UPDATE AUTOFORNE
SET
  DTMESAUTOFOR = AUTOFORNE.DTAUTOFORN - DAY(AUTOFORNE.DTAUTOFORN) + 1
WHERE
  DTMESAUTOFOR IS NULL
GO
