17

I have a column in sql server 2012 which contain white spaces. I want to replace these empty spaces with NULL. I have written the following query but its not working.

SELECT replace(COLUMN1, '',NULL) 
FROM Orders;

How to achieve the above functionality. Thanks in advance.

4 Answers 4

43

Use nullif

select nullif(Column1, '') from Orders
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks dear, its giving the desired result. before mark as answer i want to ask that how nullif compare with empty space and convert into NULL, can you please clarify me little??? Really appreciate your help, thanks.
@user3004110 NULLIF will return NULL if the value is equal to the second argument.
What this answer misses is why it works if Column1 contains ' ': string comparisons in SQL Server ignore trailing whitespace, so 'a ' and 'a' compare as equal, and similarly for ' ' and ''.
Adding a note here that NULLIF matching on an empty string returns NULL even if the column value has any number of whitespace characters (e.g. '', ' ', ' ').
2

If you want to handle the situation where the value consists of spaces or has zero length, then use ltrim() or like:

 select (case when value like '%[^ ]%' then value end)

Similarly,

select (case when ltrim(value) <> '' then value end)

2 Comments

There is no need for such complexity. My answer will handle this situation as well.
@podiluska . . . Relying on the fact that '' is equal to ' ' seems confusing to me. I prefer to be explicit about such logic.
2

The query below:

select REPLACE(ColumnName,'',NULL)as tb from TableName 

can not be used as it returns all value of this column with NULL only. Because if any parameter of Replace function is null then it returns only NULL.

It can be advisable to use NULLIF(columnName, '').

Comments

0
declare @Blank nvarchar(1)=''

SELECT nullif(COLUMN1,@Blank) 
FROM Orders;

Its select all COLUMN1 records as null if thay are blank.

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.