带空字符串的SQL Coalesce


73

我有以下内容:

Select Coalesce(Other,Industry) Ind from registration

问题是Other可以是空字符串或NULL。我如何coalesce工作,以便如果Other是空字符串,Coalesce仍然返回Industry


2
如何看待合并,因为它似乎不是标准?
Guffa 2013年

Answers:


161

使用CASE表达式或NULLIF

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

19

尝试这个

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

5

您也可以使用捷径知道NULL <> ''不会评估为TRUE...

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

逻辑如下:

  • CASE WHEN 'fubar' <> '' THEN other ELSE industry END
    => CASE WHEN true THEN other ELSE industry END
    =>other

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

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.