51

How does one detect whether a field is blank (not null) and then select another field if it is?

What I really need is a IsBlank function that works the same as IsNull but with with blanks.

REPLACE doesn't work with blanks, COALESCE only works with NULLS.

graham.reeds
  • 16,230
  • 17
  • 74
  • 137

4 Answers4

122

How about combining COALESCE and NULLIF.

SELECT COALESCE(NULLIF(SomeColumn,''), ReplacementColumn)
FROM SomeTable
PHeiberg
  • 29,411
  • 6
  • 59
  • 81
19

You can use a CASE statement for this

select 
Case WHEN Column1 = '' OR Column1 IS NULL OR LEN (TRIM (Column1))  = 0 
     THEN Column2 
     ELSE Column1 END as ColumnName
from TableName
Raj More
  • 47,048
  • 33
  • 131
  • 198
5

EDIT: You can't use IF() in mssql.

Use an IF statement in the SELECT portion of your SQL:

SELECT IF(field1 != '', field1, field2) AS myfield FROM ...
MDCore
  • 17,583
  • 8
  • 43
  • 48
  • Nice, but if I need to work more than 2 columns will be a pain. – graham.reeds Nov 17 '09 at 10:14
  • 1
    I can't seem to get it working: `SELECT IF(Address2!='', Address2, Address3) AS Address FROM Sites` gives Incorrect syntax near the keyword 'IF'. – graham.reeds Nov 17 '09 at 10:20
  • 2
    Okay, I'm a total dumbass and getting confused with mysql. `IF()` only seems to work with mysql, so rather use `CASE WHEN THEN ELSE END` as above. I'll leave this here as a warning to others :) – MDCore Nov 17 '09 at 11:31
2

You could always write an isBlank() function, something like

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE FUNCTION isBlank
(
    @CheckExpression varchar, @ReplacementExpression varchar
)
RETURNS varchar
AS
BEGIN
    IF @CheckExpression IS NOT NULL
    BEGIN
        IF @CheckExpression='' or LEN(@CheckExpression) = 0
        RETURN @ReplacementExpression
    ELSE
        RETURN @CheckExpression
    END

    RETURN @ReplacementExpression
END
GO
Chris Welsh
  • 349
  • 1
  • 2
  • 8
  • I assume you could make it support *N* number of expressions since COALESCE does anyway via case statement like Raj More. – graham.reeds Nov 17 '09 at 13:11