Masoom
Masoom

Reputation: 23

Select Column2 if Column1 is Empty or NULL

Is there any method or function in SQL Server to SELECT Column2 if Column1 is empty or NULL?

SELECT IsEmpty(Column1,Column2) FROM Table

Upvotes: 2

Views: 2482

Answers (2)

Martin Smith
Martin Smith

Reputation: 453786

SELECT CASE WHEN Column1 <> '' THEN Column1 ELSE Column2 END  

(Column1 <> '' doesn't evaluate to true when it is NULL either)

Or

SELECT COALESCE(NULLIF(Column1,''),Column2)

Upvotes: 2

twoleggedhorse
twoleggedhorse

Reputation: 5048

SELECT CASE WHEN ISNULL(Column1,'')='' THEN Column2 ELSE Column1 END FROM Table

ISNULL(Column1,Column2) will return Column2 if Column1 is NULL. If Column1 is an empty string, it will return Column1. This is why you have to test for it using a case statement like the one above.

Upvotes: 0

Related Questions