Personally I don't like the nested NULLIF and ISNULL in some of the other answers. I find this logic difficult to follow and prefer using a simple IIF( condition, true_value, else_value )
SQL uses three valued logic true, false and unknown.
With IIF if the condition evaluates to true you go through to the first case, otherwise (when it is false or unknown) you go through to the else case.
Comparisons with NULL (whether = or <> or LIKE or NOT LIKE) will evaluate as unknown.
So you just have to take care to think about the semantics you want and express it in a manner that empty string will be either bucketed with or without NULL as desired.
One other thing to be aware of is that SQL Server usually ignores trailing spaces for LEN or string comparisons. It does treat them as significant in the value on the LHS of LIKE however.
So the following expressions provide a variety of different semantics to choose the desired one from.
SELECT
ValueUnderTest
,StringLength = DATALENGTH(ValueUnderTest)
,IsEmpty = IIF(ValueUnderTest = '', 'True', 'False')
,IsNullOrEmpty = IIF(ValueUnderTest <> '', 'False', 'True')
,IsZeroLength = IIF('' LIKE ValueUnderTest, 'True', 'False')
,IsNullOrZeroLength = IIF('' NOT LIKE ValueUnderTest, 'False', 'True')
FROM
(
VALUES (''),
(' '),
(NULL),
('Fish')
) TestData(ValueUnderTest)
Returns
| ValueUnderTest |
StringLength |
IsEmpty |
IsNullOrEmpty |
IsZeroLength |
IsNullOrZeroLength |
|
0 |
True |
True |
True |
True |
|
1 |
True |
True |
False |
False |
| NULL |
NULL |
False |
True |
False |
True |
| Fish |
4 |
False |
False |
False |
False |