SQL使用空字符串进行合并

Nat*_*Pet 60 sql sql-server

我有以下内容:

     Select Coalesce(Other,Industry) Ind from registration
Run Code Online (Sandbox Code Playgroud)

问题是其他可以是空字符串或NULL.如何使cowellce工作,如果Other是一个空字符串,Coalesce仍然应该按照它应该的行为?

Lam*_*mak 128

使用CASE表达式或NULLIF:

SELECT COALESCE(NULLIF(Other,''),Industry) Ind FROM registration
Run Code Online (Sandbox Code Playgroud)


rs.*_*rs. 16

试试这个

Select Coalesce(nullif(Other,''),Industry) Ind from registration
Run Code Online (Sandbox Code Playgroud)


Mat*_*lie 5

您还可以使用NULL <> ''不评估为TRUE...的快捷方式

CASE WHEN other <> '' THEN other ELSE industry END
Run Code Online (Sandbox Code Playgroud)

然后逻辑如下......

  • 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