Logging Experiences

T-SQL: checking if a string is empty or white-space

Posted in Programming, SQL, Tips and Tricks by Sina Iravanian on September 6, 2012

Consider a case where you want to bring through a varchar column called SomeColumn from table SomeTable and replace its value with, 'Not Available' if the value is NULL or an empty string. This is how it can be achieved in Transact-SQL:

SELECT ISNULL(NULLIF(SomeTable.SomeColumn, ''), 'Not Available')
FROM SomeTable
...

The above code is checking for null or emptiness of the string. To check for being null or white-space, use the following code instead:

SELECT ISNULL(NULLIF(LTRIM(RTRIM(SomeTable.SomeColumn)), ''), 'Not Available')
FROM SomeTable
...
Advertisements
Tagged with: , ,