sql - 如何检查某些表是否为空?

标签 sql sql-server

如何在一个查询 (SQL Server) 中检查某些数据表(例如“tableA”、“tableB”和“tableC”)是否为空?

预期结果: 对我来说最重要的是获得一个结果。

  • 它可能是true(如果所有表都是空的)与false
  • 另一种可能性是所有表中所有条目的总和,例如 0(如果所有表都是空的)或 n

示例

数据库中有三张表:table1,table2,table3。

  1. 所有的 table 都是空的。 --> 预期结果:0
  2. 表 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/

相关文章:

javascript - 如何在选择查询中分配字符串变量

php - 将独特的错误与其余错误分开

php - '成功'/'updated' 消息取决于操作

mysql - 我如何在 SQL 中引用保留字以便它适用于所有常见的数据库系统?

sql - 夏令时和 UTC 时间

mysql - SQL Server 中 mysql 的等效语法

mysql - 如果使用 SQL 某些表中存在行,则更新表行

sql-server - Entity Framework 6 映射或计算列中的 Code First VarBinary 长度

c# - 在 SQL Server 2008 中实现(日期 - 时间增量)

sql-server - SQL Server 中的查询持续时间估计