多种解决方案(列包含一些NULL值 | 列全部为NULL值 * 测试单个列 | 测试多个列并获得表格结果)
如果您需要测试多个列,可以使用以下方法:
Column_1 Column_2 Column_3
1 2 NULL
1 NULL NULL
5 6 NULL
首先,测试 NULL 值并计数:
select
sum(case when Column_1 is null then 1 else 0 end) as Column_1,
sum(case when Column_2 is null then 1 else 0 end) as Column_2,
sum(case when Column_3 is null then 1 else 0 end) as Column_3,
from TestTable
返回 NULL 的数量:
Column_1 Column_2 Column_3
0 1 3
当结果为0时,表示没有NULL。
第二步,让我们统计非NULL值:
select
sum(case when Column_1 is null then 0 else 1 end) as Column_1,
sum(case when Column_2 is null then 0 else 1 end) as Column_2,
sum(case when Column_3 is null then 0 else 1 end) as Column_3,
from TestTable
但因为我们在统计非 NULL 值,所以可以简化为:
select
count(Column_1) as Column_1,
count(Column_2) as Column_2,
count(Column_3) as Column_3,
from TestTable
任何一种都可以产生:
Column_1 Column_2 Column_3
3 2 0
当结果为0时,该列完全由NULL组成。
最后,如果您只需要检查特定列,则使用TOP 1会更快,因为它应该在第一个命中时停止。然后,您可以选择使用count(*)来给出布尔风格的结果:
select count(*) from (select top 1 'There is at least one NULL' AS note from TestTable where Column_3 is NULL) a
0 = 没有 NULL,1 = 至少有一个 NULL
select count(*) from (select top 1 'There is at least one non-NULL' AS note from TestTable where Column_3 is not NULL) a
0 = 它们都是 NULL,1 = 至少有一个非 NULL
希望这可以帮到你。