SQL 显示所有表所占存储空间

时间:2023-03-08 17:40:13
SQL 显示所有表所占存储空间
USE master
SELECT
dbname = DB_NAME(),
name,
[已分配MB] = reserved*8/1024,
[已使用MB] = used*8/1024,
[未使用MB] = (CASE WHEN reserved > used THEN reserved-used else 0 END)*8/1024,
[使用率] = (CASE WHEN (reserved <= 0 OR reserved <= used) THEN 100 ELSE (used)*100/reserved END),
[数据MB] = data*8/1024,
[索引MB] = (CASE WHEN used > data THEN used-data ELSE 0 END)*8/1024,
[记录数] = rowcounts
FROM
(
SELECT
o.name,
SUM(p.reserved_page_count) AS reserved,
SUM(p.used_page_count) AS used,
SUM(CASE WHEN (p.index_id) < 2 THEN (p.in_row_data_page_count + p.lob_used_page_count + p.row_overflow_used_page_count) ELSE (p.lob_used_page_count + p.row_overflow_used_page_count) END) AS Data,
SUM(CASE WHEN (p.index_id) < 2 THEN row_count ELSE 0 END) AS rowcounts
FROM sys.objects o
INNER JOIN sys.dm_db_partition_stats p
ON p.object_id = o.object_id
--WHERE o.is_ms_shipped = 0
GROUP BY o.name
) T
ORDER BY [已分配MB] DESC