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

CREATE FUNCTION dbo.CF_Seg_User_Validar_Ip (@Id_Usuario SMALLINT,@Ip VARCHAR(20) )
RETURNS TINYINT
AS

BEGIN
DECLARE @Retorno TINYINT
		,@Cant  INT
		,@Flag_IP_NoFiltrar  TINYINT

IF (@Id_Usuario = -1)   --Admin entra directo
	RETURN 1

		
IF COL_LENGTH('Empresas_IP', 'IP') IS NULL 
	RETURN 1

SET @Cant = ISNULL( (SELECT COUNT(*) FROM Empresas_IP) ,0 )

IF @Cant = 0
	RETURN 1

SET @Flag_IP_NoFiltrar = ISNULL((SELECT Flag_IP_NoFiltrar FROM Seg_User S WHERE S.NO = @Id_Usuario) , 0)
IF @Flag_IP_NoFiltrar = 1
	RETURN 1

IF (SELECT 1 FROM Empresas_IP I WHERE I.Ip = @Ip) = 1
	RETURN 1


RETURN 0

END
