检查是否有任何列是非NULL

bit*_*ler 17 sql t-sql sql-server

我需要在SQL语句中检查列是否为NULL.

我的SQL查询:

select column_a, column_b, column_c, column_d, column_x
from myTable
Run Code Online (Sandbox Code Playgroud)

我的选择中有很多专栏.所以我遇到了性能问题,如果我会做以下事情:

select column_a, column_b, column_c, column_d, column_x
from myTable
where column_a is not null or column_b is not null or column_c is not null 
or column_x  is not null
Run Code Online (Sandbox Code Playgroud)

是否有另一种(更好的)方法来检查是否有任何列为NOT NULL?

Red*_*ter 25

你可以用COALESCE它.COALESCE返回第一个非null值(如果有).这可能不会更好,但更具可读性.

例:

where coalesce(column_a, column_b, column_c, column_x) is not null 
Run Code Online (Sandbox Code Playgroud)

根据数据的基数,您可以添加索引以帮助提高性能.

另一种可能性是使用持久计算列来告诉您是否所有四列都是NULL.

  • @Brad:OP正在选择任何列******的位置.`COALESCE`非常适用于此,并且提供的信息不会比原始查询更多或更少. (4认同)