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

CREATE TRIGGER ATUALIZA_VRDEVOLUCAOREC
ON DEVOLUCAOREC
FOR DELETE
AS
BEGIN

   DECLARE @V_VRDEVOLUCAOREC  DOUBLE PRECISION;
   DECLARE @V_CDFILIAL        VARCHAR(4);
   DECLARE @V_NRLANCTONF      VARCHAR(10);

   DECLARE C_DEVOLUCAOREC CURSOR FOR
     SELECT
       CDFILIAL,
       NRLANCTONF,
       VRDEVOLUCAOREC
     FROM
       DELETED
     WHERE
       0 = (SELECT COUNT(*) FROM INSERTED)

   OPEN C_DEVOLUCAOREC;
   FETCH NEXT FROM C_DEVOLUCAOREC INTO @V_VRDEVOLUCAOREC, @V_CDFILIAL,  @V_NRLANCTONF;

   WHILE (@@FETCH_STATUS = 0)
   BEGIN

      UPDATE NOTAFISCAL
         SET VRDEVOLNFUTL = ISNULL(VRDEVOLNFUTL, 0) - @V_VRDEVOLUCAOREC
       WHERE CDFILIAL = @V_CDFILIAL
         AND NRLANCTONF = @V_NRLANCTONF;

      FETCH NEXT FROM C_DEVOLUCAOREC INTO @V_VRDEVOLUCAOREC, @V_CDFILIAL,  @V_NRLANCTONF;
   END;

   CLOSE C_DEVOLUCAOREC;
   DEALLOCATE C_DEVOLUCAOREC;
END;
GO

-- VERSAO --
EXEC ATUVEROBJ 'ATUALIZA_VRDEVOLUCAOREC','5.07.014';
GO

