具有空字符串的 SQL Coalesce

我有以下条件:

Select Coalesce(Other,Industry) Ind from registration

问题是 Other可以是空字符串或 NULL。 如何让 coalesce工作,使得如果 Other是一个空字符串,Coalesce仍然返回 Industry

72850 次浏览

Use a CASE expression or NULLIF:

SELECT COALESCE(NULLIF(Other,''),Industry) Ind FROM registration

try this

Select Coalesce(nullif(Other,''),Industry) Ind from registration

You can also use a short-cut knowing that NULL <> '' doesn't evaluate to TRUE...

CASE WHEN other <> '' THEN other ELSE industry END

The logic then works out as follows...


  • => CASE WHEN true THEN other ELSE industry END
    => other


  • => CASE WHEN false THEN other ELSE industry END
    => industry


  • => CASE WHEN NULL THEN other ELSE industry END
    => industry