IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'[dbo].[CF_Cta_Cont]') and [type] = 'FN')
BEGIN
    DROP FUNCTION [dbo].[CF_Cta_Cont] 
END
GO


CREATE FUNCTION [dbo].[CF_Cta_Cont]  (@Alias INT,@Fecha DATETIME) 
RETURNS INT
AS
BEGIN

DECLARE @Retorno INT

SET @Retorno = (SELECT MAX(Id_Cta_Contable) 
		FROM Pla_Ctas_Cuentas_Contables C, dbo.Plan_Ctas T, Plan_Ctas_Ejercicios E
		WHERE C.Id_Plan_Cta = T.Id_Plan_Cta
		AND E.Id_Ejercicio = T.Id_Ejercicio
		AND E.Fecha_Inicio < @Fecha + 1
		AND E.Fecha_Cierre >= @Fecha
		AND C.Alias = @Alias
	) 
		

RETURN @Retorno
END
