How to find largest objects in a SQL Server database?

前端 未结 7 1407
说谎
说谎 2020-12-22 15:00

How would I go about finding the largest objects in a SQL Server database? First, by determining which tables (and related indices) are the largest and then determining whi

7条回答
  •  醉酒成梦
    2020-12-22 15:23

    I've been using this SQL script (which I got from someone, somewhere - can't reconstruct who it came from) for ages and it's helped me quite a bit understanding and determining the size of indices and tables:

    SELECT 
        t.name AS TableName,
        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.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
    WHERE 
        t.name NOT LIKE 'dt%' AND
        i.object_id > 255 AND  
        i.index_id <= 1
    GROUP BY 
        t.name, i.object_id, i.index_id, i.name 
    ORDER BY 
        object_name(i.object_id) 
    

    Of course, you can use another ordering criteria, e.g.

    ORDER BY SUM(p.rows) DESC
    

    to get the tables with the most rows, or

    ORDER BY SUM(a.total_pages) DESC
    

    to get the tables with the most pages (8K blocks) used.

提交回复
热议问题