How to count empty tables in database?

后端 未结 3 962
盖世英雄少女心
盖世英雄少女心 2020-12-31 10:23

Is there any way to count tables with no rows in my database with using T-SQL statement?

相关标签:
3条回答
  • 2020-12-31 10:48

    I use the following:

    SELECT t.NAME AS TableName, sum(p.rows) as RowCounts
        FROM sys.tables t
    INNER JOIN sys.indexes i
        ON t.OBJECT_ID = i.object_id
    INNER JOIN sys.partitions p
        ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
    WHERE
        i.name IS NULL AND i.index_id <= 1
    GROUP BY 
        t.NAME, i.object_id, i.index_id, i.name 
    HAVING SUM(p.rows) = 0
    
    0 讨论(0)
  • 2020-12-31 10:49

    from khtan @ SQL Server Forums, this is used to drop all empty tables, maybe you could adapt it to output a count?

    declare @name varchar(128), @sql nvarchar(2000), @i int
    select  @name = ''
    while   @name < (select max(name) from sysobjects where xtype = 'U')
    begin
        select @name = min(name) from sysobjects where xtype = 'U' and name > @name
        select @sql = 'select @i = count(*) from [' + @name + ']'
        exec sp_executesql @sql, N'@i int out', @i out
        if @i = 0
        begin
            select @sql = 'drop table [' + @name + ']'
            print @sql
                -- unmask next to drop the table
            -- exec (@sql)
        end
    end
    

    I don't have SQLServer here but I could take a stab at it if you like.

    0 讨论(0)
  • 2020-12-31 10:51

    There you go... using a derived table.

    SELECT * FROM
    (
     SELECT 
      [TableName] = so.name, 
      [RowCount] = MAX(si.rows) 
     FROM 
      sysobjects so, 
      sysindexes si 
     WHERE 
      so.xtype = 'U' 
      AND 
      si.id = OBJECT_ID(so.name) 
     GROUP BY 
      so.name 
    ) sub
    WHERE sub.[RowCount] = 0
    
    0 讨论(0)
提交回复
热议问题