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

CREATE FUNCTION [dbo].[CF_CtrlPresup_MesPesup] (	@mes INT
													,@Anio INT
													,@Id_Centro_Costo char(10)
													,@Alias INT)
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  = (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_Proyectos 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)) 

RETURN @IMPORTE

END 




