SQL Server 查询数据库表占用的空间及行数

–查询所有表名
SELECT name, object_id, principal_id, schema_id, parent_object_id, type, type_desc, create_date, modify_date, is_ms_shipped, is_published,
is_schema_published, lob_data_space_id, filestream_data_space_id, max_column_id_used, lock_on_bulk_load, uses_ansi_nulls, is_replicated,
has_replication_filter, is_merge_published, is_sync_tran_subscribed, has_unchecked_assembly_data, text_in_row_limit,
large_value_types_out_of_row
FROM sys.tables

–查询数据库中所有的表名及行数
SELECT a.name, b.rows
FROM sys.sysobjects AS a INNER JOIN
sys.sysindexes AS b ON a.id = b.id
WHERE (b.indid IN (0, 1)) AND (a.type = ‘u’)
ORDER BY a.name, b.rows DESC

–查询所有的表名及空间占用量\行数
SELECT OBJECT_NAME(id) AS tablename, 8 * reserved / 1024 AS reserved, RTRIM(8 * dpages) + ‘KB’ AS used, 8 * (reserved – dpages) / 1024 AS unused,
8 * dpages / 1024 – rows / 1024 * minlen / 1024 AS free
FROM sys.sysindexes
WHERE (indid = 1)
ORDER BY tablename, reserved DESC

–查询表空间占用(更准确)

SELECT
t.NAME AS TableName,
s.Name AS SchemaName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceMB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB,
(SUM(a.total_pages) – SUM(a.used_pages)) * 8 AS UnusedSpaceKB,
CAST(ROUND(((SUM(a.total_pages) – SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB
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
ORDER BY
p.rows desc

留下评论