       DECLARE @CodProv    varchar(10)
       DECLARE @ActProv    varchar(10)
       DECLARE @Monto      decimal(13,2)
       DECLARE @NroUnico   INT
       DECLARE @Saldo      decimal(13,2)
       DECLARE @FECHAE     datetime
       DECLARE @NumeroD    varchar(10)
       DECLARE @TipoCxp    varchar(2)
       DECLARE @Saldoact   decimal(13,2)
       DECLARE @FACTOR     SMALLINT
       DECLARE @Saldoant   DECIMAL(13,2)
       DECLARE MProv CURSOR FOR
       SELECT DISTINCT A.CodProv 
       FROM SAPROV A, SAACXP as B
       Where A.CodProv = B.CodProv
       Order By A.CodProv
       OPEN MProv
       FETCH NEXT FROM MProv INTO @ACTProv
       	WHILE @@FETCH_STATUS=0 BEGIN
       	   SET @SALDOANT=0
                  DECLARE MCURSOR CURSOR FOR
                  SELECT A.CodProv, A.FechaE, A.NroUnico, A.NumeroD,
                         A.TipoCxP, A.Monto,  A.Saldo,    A.Saldoact
                  FROM SAACXP as A
       	   Where A.CodProv = @ACTPROV
                  ORDER BY CodProv, A.FechaE, A.NroUnico
                  OPEN Mcursor
                  FETCH NEXT FROM Mcursor INTO @CodProv, @FECHAE, @NroUnico, @NumeroD,
                                            @TipoCxP, @Monto,  @Saldo,    @Saldoact
                  WHILE (@@FETCH_STATUS<>-1)
                   BEGIN
                     IF (@@FETCH_STATUS<>-2)
                        BEGIN
                          SET @FACTOR=CASE SUBSTRING(@TIPOCXP,1,1)
                                       WHEN '1' THEN 1
                                       WHEN '3' THEN 1
                                       WHEN '2' THEN -1
                                       WHEN '4' THEN -1
                                       WHEN '5' THEN -1
                                       WHEN '6' THEN 1
                                       WHEN '7' THEN 1
                                       WHEN '8' THEN -1  
                                      END
                          IF (SUBSTRING(@TIPOCXP,1,1) <>'5')
                             SET @SALDOANT=@SALDOANT+@FACTOR*@MONTO
                          UPDATE SAACXP
                          SET SALDOACT = @saldoant
                          WHERE NroUnico = @NroUnico
                        END
                     FETCH NEXT
                     FROM Mcursor
                     INTO @Codprov, @FECHAE, @NroUnico, @NumeroD,
                          @TipoCxP, @Monto,  @Saldo, @Saldoact
                   END
                  CLOSE MCursor
                  DEALLOCATE MCursor
       	   FETCH NEXT FROM MProv INTO @ACTPROV
       END
       CLOSE MProv
       DEALLOCATE MProv

