IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'[dbo].[CF_CtrlPresup_MesPesup]') 
                   and [type] = 'FN')
BEGIN
    DROP FUNCTION [dbo].[CF_CtrlPresup_MesPesup] 
END
GO
/*   -----------------------------Este SP queda obsoleto -------------------------------------*/
IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'[dbo].[[CP_CtrlPresup_MesPesup_Recur]]') 
                   and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
    DROP PROCEDURE [dbo].[CP_CtrlPresup_MesPesup_Recur] 
END
GO
/*--------------------------------------------------------------------------------------------*/

CREATE FUNCTION [dbo].[CF_CtrlPresup_MesPesup] (	@mes INT
													,@Anio INT
													,@Id_Centro_Costo char(10)
													,@Alias INT
													,@Flag_Recur TINYINT)
RETURNS DECIMAL(16,2)
AS
BEGIN

IF @Anio = 0	
	RETURN 0;

IF @Alias = 0	
	RETURN 0;



DECLARE @IMPORTE DECIMAL(16,2)
		,@Mes_D  SMALLINT
		,@Mes_H  SMALLINT

IF @mes = 0
BEGIN
	SET	@Mes_D  = 1
	SET @Mes_H  = 12
END
ELSE
BEGIN
	SET	@Mes_D  = @mes
	SET @Mes_H  = @mes
END


SET @IMPORTE = 0

IF ISNULL(@Id_Centro_Costo,'') = ''
BEGIN
	SET @IMPORTE  = (ISNULL((SELECT SUM(ISNULL(O.Debe,0)) - SUM(ISNULL(O.Haber,0)) as importe
								  FROM Cbtes_Ctas_Contables O, Cbtes C, Cbtes_Tipos T
								  WHERE O.Id_Trans = C.Id_Trans 
								  AND T.Id_Tipo_Cbte = C.Id_Tipo_Cbte
								  AND T.Compromete_CtrlPresup IN (1,-1)
								  AND DATEPART(mm,C.Fecha) BETWEEN @Mes_D AND @Mes_H  
								  AND DATEPART(YYYY,C.Fecha) = @Anio
								  and c.Id_Estado_Cbte  in (2,4)
								  AND O.Alias = @Alias),0)) 
END
ELSE
BEGIN
	SET @IMPORTE  = (ISNULL((SELECT SUM(ISNULL(O.Debe,0)) - SUM(ISNULL(O.Haber,0)) as importe
								  FROM Cbtes_Ctas_Contables O, Cbtes C, Cbtes_Tipos T
								  WHERE O.Id_Trans = C.Id_Trans 
								  AND T.Id_Tipo_Cbte = C.Id_Tipo_Cbte
								  AND T.Compromete_CtrlPresup IN (1,-1)
								  AND DATEPART(mm,C.Fecha) BETWEEN @Mes_D AND @Mes_H  
								  AND DATEPART(YYYY,C.Fecha) = @Anio
								  AND ISNULL(C.Id_Centro_Costo,'') = ISNULL(@Id_Centro_Costo,'')
								  and c.Id_Estado_Cbte  in (2,4)
								  AND O.Alias = @Alias),0)) 

	/*Recursividad*/

	IF ISNULL(@Flag_Recur,0) <> 0
	BEGIN
		DECLARE Cur_CF_CtrlPresup_MesPesup CURSOR FOR SELECT Id_Centro_Costo FROM Centro_Costos WHERE Id_Centro_Costo_Padre = @Id_Centro_Costo
		OPEN Cur_CF_CtrlPresup_MesPesup
		FETCH NEXT FROM Cur_CF_CtrlPresup_MesPesup INTO @Id_Centro_Costo
		WHILE @@FETCH_STATUS=0
		BEGIN
			SET @IMPORTE = @IMPORTE + dbo.CF_CtrlPresup_MesPesup(@mes, @Anio, @Id_Centro_Costo ,@Alias ,@Flag_Recur)
			FETCH NEXT FROM Cur_CF_CtrlPresup_MesPesup INTO @Id_Centro_Costo
		END
		CLOSE Cur_CF_CtrlPresup_MesPesup
		DEALLOCATE Cur_CF_CtrlPresup_MesPesup
	END
	/*fin recursivad*/
END

RETURN @IMPORTE

END 




