Table and Index size in SQL Server

前端 未结 9 1184
-上瘾入骨i
-上瘾入骨i 2020-12-04 05:41

Can we have a SQL query which will basically help in viewing table and index sizes in SQl Server.

How SQL server maintains memory usage for tables/indexes?

9条回答
  •  北海茫月
    2020-12-04 06:15

    This query comes from two other answers:

    Get size of all tables in database

    How to find largest objects in a SQL Server database?

    , but I enhanced this to be universal. It uses sys.objects dictionary:

    SELECT 
        s.NAME as SCHEMA_NAME,
        t.NAME AS OBJ_NAME,
        t.type_desc as OBJ_TYPE,
        i.name as indexName,
        sum(p.rows) as RowCounts,
        sum(a.total_pages) as TotalPages, 
        sum(a.used_pages) as UsedPages, 
        sum(a.data_pages) as DataPages,
        (sum(a.total_pages) * 8) / 1024 as TotalSpaceMB, 
        (sum(a.used_pages) * 8) / 1024 as UsedSpaceMB, 
        (sum(a.data_pages) * 8) / 1024 as DataSpaceMB
    FROM 
        sys.objects t
    INNER JOIN
        sys.schemas s ON t.SCHEMA_ID = s.SCHEMA_ID 
    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
    WHERE 
        t.NAME NOT LIKE 'dt%' AND
        i.OBJECT_ID > 255 AND   
        i.index_id <= 1
    GROUP BY 
        s.NAME, t.NAME, t.type_desc, i.object_id, i.index_id, i.name 
    ORDER BY
        sum(a.total_pages) DESC
    ;
    

提交回复
热议问题