Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL bypass REPLACE by CASE statement

I have data where some records contain blank rows (=no space, no NULL). E.g.:

LOCALE
en-es
en-uk

uk-uk

When I want to select that blank row, it's easy with:

SELECT LOCALE
FROM ABC
WHERE LOCALE = ''

But when I try to replace it as follows, it does not work, the result is still blank row:

SELECT REPLACE(LOCALE,'','WHY') AS 'LOCALE'
FROM ABC
WHERE LOCALE = ''

But if I bypass this with CASE statement, it works:

SELECT CASE
       WHEN LOCALE LIKE '' THEN 'WHY'
       ELSE LOCALE
       END AS 'LOCALE'
FROM ABC
WHERE LOCALE = ''

What is the problem here? Why does REPLACE function not work?

like image 406
DNac Avatar asked Jun 11 '15 06:06

DNac


People also ask

What is alternative to case in SQL?

Question: What is Alternative to CASE Statement in SQL Server? Answer: IIF Function.

Can I use select statement in case statement in SQL?

The case statement in SQL returns a value on a specified condition. We can use a Case statement in select queries along with Where, Order By, and Group By clause.

How do I replace multiple characters in a string in SQL Server?

If you wanted to replace the words with blank string, go with REGEXP_REPLACE() . If you want to replace the words with other words, for example replacing & with and then use replace() . If there are multiple words to be replaced, use multiple nested replace() .

Can we use aggregate function in case statement?

CASE statement in SQL and aggregate functions Aggregate functions in SQL Server perform calculations and return a single value. Examples of aggregate functions are MIN, MAX, COUNT, ABG and CHECKSUM. For this purpose, we use the COUNT aggregate function in SQL Server.


2 Answers

It is obvious that '' means blank (Not null) and it exists between two consecutive letters also. (As it is blank)

So Sql can not go on replacing that blank in between every letter with the string you want. That's why you can not replace ''

Check this query

SELECT ISNULL(NULLIF(LOCALE, ''),'WHY') AS [LOCALE]
FROM ABC
WHERE LOCALE = ''
like image 54
ThePravinDeshmukh Avatar answered Oct 03 '22 19:10

ThePravinDeshmukh


Your replace function not replace blank space. Try to this

SELECT REPLACE(isnull(ITEM,''),' ','WHY') AS 'LOCALE'
FROM Table1
WHERE ITEM = ''
like image 29
Mukesh Kalgude Avatar answered Oct 03 '22 18:10

Mukesh Kalgude