--ATUALIZA_UPDATE_NOTAFISCAL
IF EXISTS (SELECT
              NAME
           FROM
              SYSOBJECTS
           WHERE
	           NAME = 'ATUALIZA_UPDATE_NOTAFISCAL' AND
	           TYPE = 'TR')

DROP TRIGGER ATUALIZA_UPDATE_NOTAFISCAL
GO

CREATE TRIGGER ATUALIZA_UPDATE_NOTAFISCAL
ON NOTAFISCAL FOR UPDATE, INSERT

AS
   DECLARE @V_NEW_DTENTRSAID     DATETIME;
   DECLARE @V_OLD_DTENTRSAID     DATETIME;

   DECLARE @V_NEW_CDFILIAL       VARCHAR(4);
   DECLARE @V_OLD_CDFILIAL       VARCHAR(4);
   DECLARE @V_NEW_NRLANCTONF     VARCHAR(10);
   DECLARE @V_OLD_NRLANCTONF     VARCHAR(10);
BEGIN

   DECLARE C_ALTERDTNF CURSOR FOR
      SELECT INSERTED.DTENTRSAID, 
             INSERTED.CDFILIAL, 
             INSERTED.NRLANCTONF,
             DELETED.DTENTRSAID, 
             DELETED.CDFILIAL, 
             DELETED.NRLANCTONF
      FROM INSERTED, DELETED 
      WHERE (INSERTED.CDFILIAL   = DELETED.CDFILIAL)   AND
            (INSERTED.NRLANCTONF = DELETED.NRLANCTONF);

   OPEN C_ALTERDTNF;
   FETCH NEXT FROM C_ALTERDTNF INTO @V_NEW_DTENTRSAID, @V_NEW_CDFILIAL,  @V_NEW_NRLANCTONF, 
                                    @V_OLD_DTENTRSAID, @V_OLD_CDFILIAL,  @V_OLD_NRLANCTONF;

   WHILE (@@FETCH_STATUS = 0) BEGIN
      IF (@V_NEW_DTENTRSAID <> @V_OLD_DTENTRSAID) BEGIN
	UPDATE NOTAFISCAL
        SET DTENTRSAIDANT = @V_OLD_DTENTRSAID
        FROM INSERTED
        WHERE
            ISNULL(NOTAFISCAL.CDFILIAL,'0')    = ISNULL(INSERTED.CDFILIAL,'0')	AND
            ISNULL(NOTAFISCAL.NRLANCTONF,'0')  = ISNULL(INSERTED.NRLANCTONF,'0') ;
      END;
      FETCH NEXT FROM C_ALTERDTNF INTO @V_NEW_DTENTRSAID, @V_NEW_CDFILIAL,  @V_NEW_NRLANCTONF, 
                                       @V_OLD_DTENTRSAID, @V_OLD_CDFILIAL,  @V_OLD_NRLANCTONF;
   END;

   CLOSE C_ALTERDTNF;
   DEALLOCATE C_ALTERDTNF;
END;

GO

-- VERSAO --
EXEC ATUVEROBJ 'ATUALIZA_UPDATE_NOTAFISCAL','5.01.017';
GO

