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

CREATE FUNCTION dbo.CF_Login_Sistema(@pUsuario VARCHAR(41), @pPassword VARCHAR(20))
RETURNS INT
AS
BEGIN

DECLARE @Flag_Login_Exitoso			INT
DECLARE @Password_Encriptada		VARCHAR(50)
DECLARE @Flag_Usuario_Tiene_Espacio BIGINT

SET @pUsuario = UPPER(LTRIM(RTRIM(@pUsuario)))
SET @pPassword = UPPER(@pPassword)
SET @Flag_Usuario_Tiene_Espacio = CHARINDEX(' ' , @pUsuario)

SET @Password_Encriptada = (dbo.SF_EncriptPassword(@pPassword))

IF(@Flag_Usuario_Tiene_Espacio = 0)
BEGIN
	SET @Flag_Login_Exitoso =  ISNULL(	(SELECT ISNULL(No, 0)
	  									FROM Seg_User
	  									WHERE 
	  									UPPER(LTRIM(RTRIM(LastName))) = @pUsuario
	  									AND UPPER(LTRIM(RTRIM(Password)))	= @Password_Encriptada)
	  								, 0)
END
ELSE
BEGIN
	SET @Flag_Login_Exitoso =  ISNULL(	(SELECT ISNULL(No, 0)
	  									FROM Seg_User
	  									WHERE 
	  									UPPER(LTRIM(RTRIM(FirstName))) + ' ' + UPPER(LTRIM(RTRIM(LastName))) = @pUsuario
	  									AND UPPER(LTRIM(RTRIM(Password)))	= @Password_Encriptada)
	  								, 0)
END

RETURN ISNULL(@Flag_Login_Exitoso, 0)
END