How to count empty tables in database?

后端 未结 3 991
盖世英雄少女心
盖世英雄少女心 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: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.

提交回复
热议问题