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

时间:2016-07-15 11:19:05

标签: sql sql-server

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

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

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

示例

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

  1. 所有表格都是空的。 - >预期结果: 0
  2. Table1有3行,table2有0行,table3有1行。 - >预期结果: 4

3 个答案:

答案 0 :(得分:7)

您可以使用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;

如果您需要准确,最新的结果,我会对使用系统表进行此操作持谨慎态度。系统表在静态环境中非常棒,表格没有变化,但我怀疑你的环境更具动态性。

答案 1 :(得分:2)

您也可以使用此DMV,它将仅从CACHE查询Count ..

SELECT  SUM(row_count) AS rows
FROM sys.dm_db_partition_stats
where object_name(object_id) in ('table1','tab1e2')
group by OBJECT_NAME(object_id)

按问题更新:

;with cte
as
(SELECT  SUM(row_count) AS rows
        FROM sys.dm_db_partition_stats
        where object_name(object_id) in ('table1','tab1e2')
        group by OBJECT_NAME(object_id))
select sum(rows) as rows from cte

答案 2 :(得分:0)

希望以下查询可以帮助您。

SELECT
        SCHEMA_NAME(SOS.SCHEMA_ID) + '.' + (SOS.NAME) AS [Table Name]
      , (SPS.Rows) AS [Row Count]
      , [Heap / Clustered Table] = CASE SPS.INDEX_ID WHEN 0 THEN 'HEAP' ELSE 'CLUSTERED' END
FROM 
      sys.objects AS SOS
      INNER JOIN sys.partitions AS SPS
            ON SOS.object_id = SPS.object_id
WHERE
      SOS.type = 'U'
      AND SPS.index_id < 2
      and SPS.Rows =0
ORDER BY [Table Name]

如果我的帖子可以帮助您,请将我标记为答案。 问候 ChetanV