提供一個實用存儲過程 get_tableinfo,掃描資料庫所有使用者表,呼叫 sp_spaceused 取得每表空間佔用,結果寫入暫存表 tablespaceinfo 供後續查詢排序。
tablespaceinfo(欄位:nameinfo、rowsinfo、reserved、datainfo、index_size、unused)。sysobjects 類型為 'U' (使用者表) 且非暫存表(not like '#%%')。sp_spaceused @tbname 並將結果寫入結果表。-- 執行掃描
exec get_tableinfo
-- 查詢結果,按保留空間降序排列
select *
from tablespaceinfo
order by cast(left(ltrim(rtrim(reserved)), len(ltrim(rtrim(reserved)))-2) as int) desc
欄位說明:reserved 總保留空間、datainfo 資料空間、index_size 索引空間、unused 未使用空間(單位通常為 KB,字串格式如 "12345 KB")。
此過程可快速定位大表、規劃歸檔、優化儲存分配,是 DBA 例行巡檢利器。