• I personally think the reason the function returns null is because of NULL concatenation math. I think the underlying code uses loops and concatentates the string piece by piece similar to the construct below. Because an empty string has no length the code cant iterate through the string correctly, thus the returned value is NULL. Even if you could determine the length of the string, the NULL concatenation would make the entire string NULL anyway.

    I think it looks something like this under the hood. (Obviously the construct is not TSQL, but the construct should be logically similar to this)

    DECLARE @i INT,

    @LenStr INT,

    @STR VARCHAR(8000),

    @Search VARCHAR(8000),

    @ReplaceWith VARCHAR(8000),

    @NewStr VARCHAR(8000)

    SET @STR = 'Hello World ->>/ this is coolz World<<-'

    SET @LenStr = DATALENGTH(@Str)

    SET @Search = 'World'

    SET @ReplaceWith = 'Worldz'--change to null to see what happens

    SET @i = 1

    SET @NewStr = ''

    WHILE @i < @LenStr+1

    BEGIN

    IF SUBSTRING(@Str,@i,DATALENGTH(@Search)) = @Search

    BEGIN

    SET @NewStr = @NewStr + @ReplaceWith

    SET @i = @i + DATALENGTH(@Search)

    END

    ELSE

    BEGIN

    SET @NewStr = @NewStr + SUBSTRING(@Str,@i,1)

    SET @i = @i + 1

    END

    END

    SELECT @NewStr