如何在一个查询 (SQL Server) 中检查某些数据表(例如“tableA”、“tableB”和“tableC”)是否为空?
预期结果: 对我来说最重要的是获得一个结果。
- 它可能是true(如果所有表都是空的)与false。
- 另一种可能性是所有表中所有条目的总和,例如 0(如果所有表都是空的)或 n。
示例
数据库中有三张表:table1,table2,table3。
- 所有的 table 都是空的。 --> 预期结果:0
- 表 1 有 3 行,表 2 有 0 行,表 3 有 1 行。 --> 预期结果:4。
最佳答案
您可以使用union all
从表中获取计数:
select 'a', count(*) from a union all
select 'b', count(*) from b union all
select 'c', count(*) from c;
然而,最快的方法是使用exists
:
select (case when not exists (select 1 from a) then 1 else 0 end) as a_is_empty,
(case when not exists (select 1 from b) then 1 else 0 end) as b_is_empty,
(case when not exists (select 1 from c) then 1 else 0 end) as c_is_empty
编辑:
如果你想要三个表的总行数,只需将它们相加即可:
select sum(cnt)
from (select 'a', count(*) as cnt from a union all
select 'b', count(*) from b union all
select 'c', count(*) from c
) abc;
如果您需要准确、最新的结果,我会谨慎使用系统表进行此操作。系统表在静态环境中非常好,表不会改变,但我怀疑您的环境更动态。
关于sql - 如何检查某些表是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38394851/