如何计算数据库中的空表?

时间:2010-01-25 13:56:43

标签: sql database sql-server-2008 tsql

有没有办法使用T-SQL语句计算数据库中没有行的表?

3 个答案:

答案 0 :(得分:15)

你去......使用派生表。

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

答案 1 :(得分:4)

我使用以下内容:

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

答案 2 :(得分:1)

来自 khtan @ SQL Server Forums,这用于删除所有空表,也许您可​​以调整它以输出计数?

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

我这里没有SQLServer,但如果你愿意,我可以试一试。