IF EXISTS (SELECT * FROM SYSOBJECTS O, SYSUSERS U
           WHERE O.NAME = 'RATEIO_PARTIDA' AND
                 TYPE = 'P' 	           AND
	              U.UID = O.UID        AND
	              U.NAME = USER)
DROP PROCEDURE RATEIO_PARTIDA
GO

CREATE PROCEDURE RATEIO_PARTIDA(
    @P_CDEMPRESA     VARCHAR(2),
    @P_CDLOTE        VARCHAR(20),
    @P_DTMOVI        DATETIME,
    @P_NRLANCLOTE    VARCHAR(6),
    @P_CDFILIAL      VARCHAR(4),
    @P_CDCENTCUST    VARCHAR(4),
    @P_VRRATECCUS    DOUBLE PRECISION)
AS
BEGIN
    DECLARE @V_RATEEXISTE     FLOAT;
    DECLARE @V_MAXSEQLANCLOTE VARCHAR(05);
    DECLARE @V_IDCONTGERE     VARCHAR(01);

    SELECT @V_MAXSEQLANCLOTE = (MAX(NRSEQLANLOTE))
      FROM LANCLOTE
     WHERE CDLOTE     = @P_CDLOTE
       AND NRLANCLOTE = @P_NRLANCLOTE;

    SELECT @V_IDCONTGERE = IDCONTGERE
      FROM CONTOPECTBL
     WHERE CDEMPRESA = @P_CDEMPRESA;

    SELECT @V_RATEEXISTE = (COUNT(*))
      FROM RATECCUS
     WHERE CDEMPRESA    = @P_CDEMPRESA
       AND CDLOTE       = @P_CDLOTE
       AND NRLANCLOTE   = @P_NRLANCLOTE
       AND NRSEQLANLOTE = @V_MAXSEQLANCLOTE
       AND CDFILIAL     = @P_CDFILIAL
       AND CDCENTCUST   = @P_CDCENTCUST;       

    IF @V_IDCONTGERE = 'S' BEGIN
       IF @V_MAXSEQLANCLOTE IS NOT NULL BEGIN
         IF @V_RATEEXISTE = 1 BEGIN
           UPDATE RATECCUS
              SET VRRATECCUS  = VRRATECCUS + @P_VRRATECCUS
            WHERE CDEMPRESA   = @P_CDEMPRESA
             AND CDLOTE       = @P_CDLOTE
             AND NRLANCLOTE   = @P_NRLANCLOTE
             AND NRSEQLANLOTE = @V_MAXSEQLANCLOTE
             AND CDFILIAL     = @P_CDFILIAL
             AND CDCENTCUST   = @P_CDCENTCUST;
         END
         ELSE
           INSERT INTO RATECCUS
             (CDEMPRESA, CDLOTE, NRLANCLOTE, NRSEQLANLOTE, CDFILIAL, CDCENTCUST, VRRATECCUS, DTCOMPRATECCUS)
           VALUES
             (@P_CDEMPRESA, @P_CDLOTE, @P_NRLANCLOTE, @V_MAXSEQLANCLOTE, @P_CDFILIAL, @P_CDCENTCUST, @P_VRRATECCUS, @P_DTMOVI);
       END;
    END;
END
GO