11

I discover some behavior I didn't know before. Why this line of code does not work?

SELECT REPLACE('','','0') ==> returns ''

I can't even have '' in where condition. It just doesn't work. I have this from imported Excel where in some cells are no values but I'm not able to remove them unless I used LEN('') = 0 function.

3
  • I tried to set in where condition an empty string and in my case it works. Commented Mar 12, 2015 at 13:34
  • I would take a look at the documentation for this. Commented Mar 12, 2015 at 13:35
  • @Galma88: it does not work as expected (from OP). It does not replace the empty string with 0. Commented Mar 12, 2015 at 13:41

4 Answers 4

22

There is nothing to replace in an empty string. REPLACE replaces a sequence of characters in a string with another set of characters.

You could use NULLIF to treat it as NULL + COALESCE (or ISNULL):

declare @value varchar(10);
set @value = '';
SELECT COALESCE(NULLIF(@value,''), '0')

This returns '0'.

Sign up to request clarification or add additional context in comments.

Comments

4

You can use CASE for this.

(CASE WHEN *YOURTHING* = '' THEN '0' ELSE *YOURTHING* END) 
AS *YOURTHING*

Comments

0

It does work. There are two proper behaviors here - first one is to return back empty string (what it does already), second one is to return infinite string full of zeroes.

1 Comment

He doesn't want to return an empty string from an already empty string. He wants to replace it with 0.
0

Solved! > Check multiple scenarios like '', remove spaces, Null, string/numeric result

 SELECT CASE WHEN LTRIM(RTRIM(ISNULL(mob, 0))) = '' THEN '0' ELSE LTRIM(RTRIM(ISNULL(mob, 0)))  END  MobileNo 
FROM table1 WHERE emp_no = '01111'

Comments

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.