CREATE OR ALTER PROCEDURE SPU_CONTA_RECEBER_SALDO (
    NFS_CONTROLE_1 INTEGER,
    CONTROLE_1 INTEGER)
RETURNS (
    CONTROLE2 INTEGER,
    CONTROLE3 INTEGER,
    DATA DATE,
    VALOR NUMERIC(10,5),
    SALDO NUMERIC(10,5),
    RM CHAR(1),
    TIPO CHAR(1))
AS
DECLARE VARIABLE CONTROLEX INTEGER;
DECLARE VARIABLE SALDOX    NUMERIC(10,2);
BEGIN
ControleX = 0;
FOR Select
A.Nfs_Parcelamento_Controle, A.Controle, A.Data,
A.Valor_Total, A.Valor_Saldo, A.Registro_Mestre, A.Tipo
From TbCaixaBanco_Lancamento_Reg A
Where A.Nfs_Controle = :Nfs_Controle_1
  and A.Nfs_Parcelamento_Controle = :Controle_1

Order By 1, 2, 3

INTO
 :Controle2,
 :Controle3,
 :Data,
 :Valor,
 :Saldo,
 :RM,
 :TIPO
DO     

 IF (:CONTROLE2 > 0) then
    BEGIN
    IF (:CONTROLEX <> :CONTROLE2) then
    BEGIN

       SALDOX = :VALOR;
       CONTROLEX = :CONTROLE2;

    END ELSE
    BEGIN

       IF (:TIPO = 'C') then
          BEGIN
          SALDOX = :SALDOX - :VALOR ;
          END
       IF (:TIPO = 'D') then
          BEGIN
          SALDOX = :SALDOX + :VALOR ;
          END
       END

       IF (:SALDOX < 0) then
           BEGIN
           SALDOX = 0;
           END

       Update TbCaixaBanco_Lancamento_Reg Set
       VALOR_SALDO = :SALDOX
       Where CONTROLE = :CONTROLE3
         and Nfs_Controle = :Nfs_Controle_1
         and NfS_Parcelamento_Controle = :CONTROLE2;

   END
END;