IF OBJECT_ID('dbo.fn_Primer_Apellido') IS NOT NULL
    DROP FUNCTION dbo.fn_Primer_Apellido
GO
CREATE FUNCTION dbo.fn_Primer_Apellido
(
    @pvc_nombre varchar(100)
)
RETURNS char(20)
AS
BEGIN
DECLARE 
    @vvc_cad varchar(20),
	@vti_long tinyint

	SET @vti_long = CharIndex('/', @pvc_nombre)

	IF @vti_long = 0
		SET @vti_long = CharIndex(' ', @pvc_nombre)

	IF @vti_long > 0
		SET @vti_long = @vti_long - 1 

    SET @vvc_cad = Substring(@pvc_nombre, 1, @vti_long)
	SET @vvc_cad = Substring(@vvc_cad,1,20)

    RETURN @vvc_cad   
END
GO
GRANT EXECUTE ON fn_Primer_Apellido TO PUBLIC
GO
