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

CREATE FUNCTION [dbo].[CF_SCA_FormatoIP](@pDireccionIP VARCHAR(15))
RETURNS VARCHAR(15)
AS
BEGIN
DECLARE @DireccionIPFormateada	VARCHAR(15)
DECLARE @Posicion	INT
DECLARE @IP_Part	VARCHAR(3)

IF(LEN(@pDireccionIP) < 15)
BEGIN

	IF((SELECT MAX(Id) FROM dbo.SF_DivisionCadena(@pDireccionIP, '.')) = 4)
	BEGIN
		DECLARE curIPFormateada CURSOR FOR 
		SELECT Id, corte FROM dbo.SF_DivisionCadena(@pDireccionIP, '.')
		ORDER BY Id

		OPEN curIPFormateada
		FETCH NEXT FROM curIPFormateada INTO @Posicion, @IP_Part
		WHILE @@FETCH_STATUS = 0
		BEGIN
			
			IF(@Posicion = 1)
			BEGIN
				SET @DireccionIPFormateada = RIGHT('000' + LTRIM(RTRIM(@IP_Part)), 3)
			END
			ELSE
			BEGIN
				SET @DireccionIPFormateada = @DireccionIPFormateada + '.' + RIGHT('000' + LTRIM(RTRIM(@IP_Part)), 3)
			END
			FETCH NEXT FROM curIPFormateada INTO @Posicion, @IP_Part
		END 
		CLOSE curIPFormateada
		DEALLOCATE curIPFormateada
	END
END
ELSE
BEGIN
	SET @DireccionIPFormateada = @pDireccionIP
END

RETURN ISNULL(@DireccionIPFormateada, '255.255.255.255')

END