IF  EXISTS (SELECT * FROM SYS.OBJECTS WHERE OBJECT_ID = OBJECT_ID(N'[P_ATUALIZA_SALDO_RC_CREDIARIO_PARC]') AND TYPE IN (N'P', N'PC'))
	DROP PROCEDURE [P_ATUALIZA_SALDO_RC_CREDIARIO_PARC]  
GO
/****** OBJECT:  STOREDPROCEDURE [DBO].[P_ATUALIZA_SALDO_RC_CREDIARIO_PARC]    SCRIPT DATE: 08/07/2015 09:48:58 ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

--EXEC P_ATUALIZA_SALDO_RC_CREDIARIO_PARC  51943
--52900

--EXEC P_ATUALIZA_SALDO_RC_CREDIARIO_PARC 4136955
CREATE PROCEDURE [P_ATUALIZA_SALDO_RC_CREDIARIO_PARC] (@CD_CTR INT)
AS

BEGIN
	
	DECLARE @VLRCRED MONEY, @VLR_PARC_CRED MONEY, @STS_CRED INT;


	SET @VLR_PARC_CRED =  ISNULL((SELECT  
										VLR_PARC_CRED
									FROM 
									RC_CREDIARIO_PARC 
								WHERE 
									CD_CTR = @CD_CTR
									AND CD_EMP=1),0)

	SET @VLRCRED  = ISNULL((SELECT 
						SUM(C.VLR_CRED) 
					FROM 
						RC_CREDIARIO_PARC_CRED C
					WHERE	C.CD_CTR = @CD_CTR),0);

	SET @STS_CRED =0;

	IF EXISTS(SELECT CD_CTR FROM RC_CREDIARIO_PARC_RC_CREDIARIO_FECHA AS FECHA 
				WHERE FECHA.CD_CTR =@CD_CTR)
		SET @STS_CRED =1

	IF EXISTS(SELECT CD_EMP 
					FROM 
						RC_CREDIARIO_PARC
					WHERE 
						RC_CREDIARIO_PARC.CD_CTR = @CD_CTR
						AND SLD_PARC_CRED <= 0
						AND STS_LANC_CRED <> 1)
		SET @STS_CRED =1 
		
	IF EXISTS(SELECT CD_EMP 
					FROM 
						RC_CREDIARIO_PARC
					WHERE 
						RC_CREDIARIO_PARC.CD_CTR = @CD_CTR
						AND SLD_PARC_CRED = VLR_PARC_CRED
						AND STS_LANC_CRED <> 1)
		SET @STS_CRED = 0 

/*******************************************************************************************************************/

	UPDATE RC_CREDIARIO_PARC 
	SET
		SLD_PARC_CRED = @VLR_PARC_CRED - @VLRCRED,
		STS_LANC_CRED = @STS_CRED
	WHERE 
		CD_CTR = @CD_CTR ;

/*******************************************************************************************************************/
			
END

GO


