0
SELECT REPLACE('hello', 'e', NULL) 
-- returns NULL

SELECT REPLACE('hello', '5', NULL) 
-- also returns NULL -- here I'd expect it does nothing since there is no '5' in 'hello'

The documentation clearly states:

Returns NULL if any one of the arguments is NULL.

So the behavior is explained.

Is there a workaround, meaning if a pattern is found in a string like 'e' in hello ; a NULL value is emitted?

3
  • 3
    If the pattern is not found in hello, then what should the output be? Commented Dec 23, 2021 at 10:02
  • 2
    Side note: SQL Server 2008 has been completely unsupported for well over 2 years; you really should be looking at upgrade paths. Commented Dec 23, 2021 at 10:17
  • @Tim Biegeleisen ; if it is not found, it should return hello. If it is found, it should return NULL. Commented Dec 23, 2021 at 10:47

1 Answer 1

3

Seems like REPLACE isn't what you are after. One method instead would be using a CASE and a LIKE:

SELECT CASE WHEN 'hello' NOT LIKE '%5%' THEN 'hello' END;

Alternatively you could use CHARINDEX:

SELECT CASE WHEN CHARINDEX('5','hello') = 0 THEN 'hello' END;
Sign up to request clarification or add additional context in comments.

2 Comments

I just tried ; but you cannot force the result to be NULL in a case :(
What do you mean, @TimBer ? Both the above will return NULL if the search character is found. db<>fiddle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.