CREATE PROCEDURE CP_CC_Prorrateo_Cta (@Id_Prorrateo SMALLINT,@Debe DECIMAL(16,2),@Haber DECIMAL(16,2))
AS 
BEGIN
SET NOCOUNT ON

DECLARE @Id_Centro_Costo CHAR(10)
	   ,@Porc DECIMAL(10,5)
	   ,@Tot_Debe DECIMAL(16,2)
	   ,@Tot_Haber DECIMAL(16,2)
	   

SELECT Id_Centro_Costo,@Debe AS Debe, @Haber AS Haber INTO #TmpProrra
       FROM Centro_Costos WHERE 1=0

DECLARE CurTmpProrra CURSOR FOR 
                    SELECT ISNULL(I.Id_Centro_Costo,''),ISNULL(I.Porc / 100,0) 
					FROM Centro_Costos_Prorra_Items I
                    WHERE I.Id_Prorrateo = @Id_Prorrateo
					

OPEN CurTmpProrra
FETCH NEXT FROM CurTmpProrra INTO @Id_Centro_Costo,@Porc
WHILE @@FETCH_STATUS=0
BEGIN
	INSERT INTO #TmpProrra VALUES (@Id_Centro_Costo, ISNULL(@Debe * @Porc,0), ISNULL(@Haber * @Porc,0))
	FETCH NEXT FROM CurTmpProrra INTO @Id_Centro_Costo,@Porc
END
CLOSE CurTmpProrra
DEALLOCATE CurTmpProrra


SET @Tot_Debe  = ISNULL((SELECT SUM(Debe)  FROM #TmpProrra),0)
SET @Tot_Haber = ISNULL((SELECT SUM(Haber) FROM #TmpProrra),0)


IF @Tot_Debe <> 0 AND @Tot_Debe <> @Debe
BEGIN
   UPDATE #TmpProrra SET Debe = Debe + @Tot_Debe - @Debe WHERE Id_Centro_Costo = @Id_Centro_Costo
END


IF @Tot_Haber <> 0 AND @Tot_Haber <> @Haber
BEGIN
   UPDATE #TmpProrra SET Haber = Haber + (@Haber - @Tot_Haber) WHERE Id_Centro_Costo = @Id_Centro_Costo
END



SELECT T.Id_Centro_Costo ,C.Descripcion,T.Debe ,T.Haber
FROM #TmpProrra T, Centro_Costos C
WHERE T.Id_Centro_Costo = C.Id_Centro_Costo

DROP TABLE #TmpProrra
END




