SQL Server找出最占存储空间的表

今天在有台服务器硬盘突然告警了,排查了一下发现是SQL Server的mdf文件太大,把硬盘给撑爆了。所以就有一个需求要在SQL Server里找出占用存储空间最多的表,进行清理。

下面是Amber和Qing贡献的一个SQL查询和运行效果。

CREATE TABLE #temp (   
table_name sysname ,   
row_count INT,   
reserved_size VARCHAR(50),   
data_size VARCHAR(50),   
index_size VARCHAR(50),   
unused_size VARCHAR(50))   
SET NOCOUNT ON   
INSERT #temp   
EXEC sp_msforeachtable 'sp_spaceused ''?'''   
SELECT a.table_name,   
a.row_count,   
COUNT(*) AS col_count,   
a.data_size   
FROM #temp a   
INNER JOIN information_schema.columns b   
ON a.table_name collate database_default   
= b.table_name collate database_default   
GROUP BY a.table_name, a.row_count, a.data_size   
ORDER BY CAST(REPLACE(a.data_size, ' KB', '') AS integer) DESC   
DROP TABLE #temp   

输出结果如下图所示

Table_Name

Row_count

Col_count

DataSize

tbl_TR_SubtaskTrail

26962623

12

48679192 KB

tbl_TR_TaskTrail

7656102

25

7120016 KB

tbl_TR_AuditTrail

3361530

8

3410224 KB

tbl_TR_TaskTrailUserAccess

23569366

5

2882992 KB

tbl_PCMT_PerfHistory_Raw

3835883

4

650904 KB

tbl_PCMT_PerfHistory_Hourly

1982372

4

342872 KB

tbl_TR_DeletedObject

1320476

4

279712 KB

tbl_PCMT_PerfHistory_Daily

1393939

4

193592 KB

tbl_WLC_VMInstance

12692

77

108144 KB

tbl_WLC_VNetworkAdapter

41212

42

100376 KB

tbl_PCMT_TieredPerfCounter

257699

41

95336 KB


Comments

43 responses to “SQL Server找出最占存储空间的表”

Leave a Reply