我们可以有一个SQL查询,它基本上有助于查看SQl Server中的表和索引大小.
SQL Server如何维护表/索引的内存使用?
sp_spaceused为您提供所有索引组合的大小.
如果您想要表的每个索引的大小,请使用以下两个查询之一:
SELECT i.name AS IndexName, SUM(s.used_page_count) * 8 AS IndexSizeKB FROM sys.dm_db_partition_stats AS s JOIN sys.indexes AS i ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id WHERE s.[object_id] = object_id('dbo.TableName') GROUP BY i.name ORDER BY i.name SELECT i.name AS IndexName, SUM(page_count * 8) AS IndexSizeKB FROM sys.dm_db_index_physical_stats( db_id(), object_id('dbo.TableName'), NULL, NULL, 'DETAILED') AS s JOIN sys.indexes AS i ON s.[object_id] = i.[object_id] AND s.index_id = i.index_id GROUP BY i.name ORDER BY i.name
结果通常略有不同,但在1%以内.
在exec sp_spaceused
无参数显示为整个数据库中的概要.foreachtable解决方案为每个表生成一个结果集 - 如果您有太多表,SSMS可能无法处理.
我创建了一个脚本,它通过收集表信息sp_spaceused
并在单个记录集中显示摘要,按大小排序.
create table #t ( name nvarchar(128), rows varchar(50), reserved varchar(50), data varchar(50), index_size varchar(50), unused varchar(50) ) declare @id nvarchar(128) declare c cursor for select '[' + sc.name + '].[' + s.name + ']' FROM sysobjects s INNER JOIN sys.schemas sc ON s.uid = sc.schema_id where s.xtype='U' open c fetch c into @id while @@fetch_status = 0 begin insert into #t exec sp_spaceused @id fetch c into @id end close c deallocate c select * from #t order by convert(int, substring(data, 1, len(data)-3)) desc drop table #t
在SQL 2012上,在表级获取此信息变得非常简单:
SQL Management Studio - >右键单击Db - > Reports - > Standard Reports - > Disk by table!
请享用
EXEC sp_MSforeachtable @command1="EXEC sp_spaceused '?'"