查找所有数据库表的表大小

时间:2017-06-09 11:19:38

标签: sql-server database

我一直在寻找几天找到一种方法来查找当前SQL实例中每个数据库的表大小。目前我能够使用sp_spaceused获取当前数据库的表大小而没有问题,有没有办法使用sp_MSforeachdb来获取大小信息?

我可以列出所有表格,但不确定如何添加表格大小。

Declare @temp_table table
(
    DB_NAME varchar(max),
    TABLE_OWNER varchar(max),
    TABLE_NAME varchar(max),
    TABLE_TYPE varchar(max),
    REMARKS varchar(max)
)

INSERT INTO @temp_table (DB_NAME, TABLE_OWNER, TABLE_NAME, TABLE_TYPE,REMARKS)
EXECUTE master.sys.sp_MSforeachdb 'USE [?]; EXEC sp_tables'

SELECT DB_NAME, TABLE_OWNER, TABLE_NAME, TABLE_TYPE
FROM @temp_table 
WHERE DB_NAME not in ('master','model','msdb','tempdb') and [TABLE_TYPE] = 'TABLE'
order by 1,2,3

欢迎任何建议。

提前致谢..

1 个答案:

答案 0 :(得分:0)

如果表格大小是您的问题,则可以按以下方式计算:

Declare @temp_table table
(
    DBNAME varchar(max),
    TABLE_Name varchar(max),
      table_schema varchar(max),
      row_count int,
    TABLE_Size_in_kb numeric(10,2) 
)

INSERT INTO @temp_table 
EXECUTE master.sys.sp_MSforeachdb 'USE [?]; SELECT 
    ''?'',
    t.NAME AS TableName,
    s.Name AS SchemaName,
    p.rows AS RowCounts,
    SUM(a.total_pages) * 8 AS TotalSpaceKB 
    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
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN 
    sys.schemas s ON t.schema_id = s.schema_id
WHERE 
    t.NAME NOT LIKE ''dt%'' 
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
GROUP BY 
    t.Name, s.Name, p.Rows'

SELECT *
FROM @temp_table 
WHERE DBNAME not in ('master','model','msdb','tempdb') 
order by 1,2,3