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

CREATE FUNCTION [dbo].[SF_Cli_Categ_Mes](@Id_Cliente INT, @fecha DATETIME)
RETURNS SMALLINT
AS
BEGIN

DECLARE @id_Tipo_Cli INT
DECLARE @max_item SMALLINT

SET @id_Tipo_Cli  = 0
SET @max_item = ISNULL(	(SELECT TOP(1) item FROM Clientes_Hist WHERE Id_cliente=@Id_Cliente AND Fecha<@fecha + 1 ORDER BY Item DESC),0)

IF (@max_item != 0)
BEGIN
   SET @id_Tipo_Cli = ISNULL((SELECT Id_Tipo_Cli FROM Clientes_Hist WHERE id_cliente=@id_cliente AND Item=@max_item), 0)
END

IF @id_Tipo_Cli = 0
   BEGIN 
      SET @id_Tipo_Cli = ISNULL((SELECT Id_Tipo_Cli FROM Clientes WHERE id_cliente = @id_cliente), 0)
   END
RETURN @Id_Tipo_Cli
END
