1

I have a table with a varchar(100) column that has some empty values. When I try to replace the empty strings with a value, nothing happens. I cannot figure out why. I am sure the value in the cells is not null. I can reproduce with a temporary table and some sample data.

The below SQL should return a result set in which the [ReplacedTextCol] always has a value, but even when using replace, I cannot replace the empty string:

create table #tempt
(
    col1 varchar(100)
)

insert into #tempt(col1) 
values('')
,('')
,('some value')

select replace(col1, '','replaced') as ReplacedTextCol,* 
from #tempt

The result of the above query is shown below:

enter image description here

Table, DB & server uses the collation SQL_Latin1_General_CP1_CI_AS

Appreciate any pointer as to where I'm going wrong.

2
  • If you think about it, it's quite logical. An empty string has no characters. How many 0-length substrings are in abcd? What you ask should either match all characters as if it were a wildcard, or none Commented Sep 23, 2020 at 16:41
  • Use case when or IIF() instead of REPLACE. You're looking for an exact match after all, not find an empty string inside another string. Eg use IIF(col1='','replaced',col1) Commented Sep 23, 2020 at 16:42

2 Answers 2

3

REPLACE doesn't work with empty strings:

string_pattern

Is the substring to be found. string_pattern can be of a character or binary data type. string_pattern cannot be an empty string (''), and must not exceed the maximum number of bytes that fits on a page.

Use simple UPDATE:

UPDATE YourTable
SET SomeColumn = 'replaced'
WHERE SomeColumn  = '';

Or SELECT:

SELECT CASE WHEN SomeColumn = '' THEN 'replaced' ELSE SomeColumn END
FROM YourTable
WHERE SomeColumn  = ''
Sign up to request clarification or add additional context in comments.

Comments

0

REPLACE is used to replace one substring with another, you want COALESCE or a SELECT CASE construct to replace empty values, try

select CASE WHEN COALESCE(col1,'') = '' THEN 'replaced' ELSE col1 END as ReplacedTextCol,* 
from #tempt

2 Comments

That's not what COALESCE is for, or what your own answer uses. This answer uses CASE WHEN to return a different value if a field contains an empty string. COALESCE replaces a null value with a specific value, which isn't needed here
COALESCE replaces a value when empty is represented as NULL, if you might have some NULL and some as an empty string (which COALESCE won't touch) you need both COALESCE and CASE, the COALESCE converts NULL to EMPTY, and the CASE checks for EMPTY and converts to the final value. Depending on the source of data, mixed NULL and EMPTY might be a big problem and this works for all.

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.