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

CREATE TRIGGER ATUALIZA_VRDEVOLUCAO
ON DEVOLUCAOPAG
FOR DELETE
AS
BEGIN

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

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

   OPEN C_DEVOLUCAO;
   FETCH NEXT FROM C_DEVOLUCAO INTO @V_VRDEVOLUCAOPAG, @V_CDFILIAL,  @V_NRLANCTONF;

   WHILE (@@FETCH_STATUS = 0)
   BEGIN

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

      FETCH NEXT FROM C_DEVOLUCAO INTO @V_VRDEVOLUCAOPAG, @V_CDFILIAL,  @V_NRLANCTONF;
   END;

   CLOSE C_DEVOLUCAO;
   DEALLOCATE C_DEVOLUCAO;
END;
GO

-- VERSAO --
EXEC ATUVEROBJ 'ATUALIZA_VRDEVOLUCAO','5.07.015';
GO

