sp_spaceused - How to measure the size in GB in all the tables in SQL

后端 未结 4 1246
离开以前
离开以前 2021-02-09 01:18

Following the discussion in How to measure table size in GB in a table in SQL, I\'m looking for a solution to measure the space used by all the tables of a SQL Server individual

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-09 01:29

    I know this isn't exactly what you are asking for as it DOESN'T use sp_spaceused but this will provide the results you are after.

    SELECT  
        s.Name AS SchemaName,
        t.NAME AS TableName,
        p.rows AS RowCounts,
        SUM(a.total_pages) * 8 AS TotalSpaceKB,
        ( SUM(a.total_pages) * 8 ) / 1024.0 AS TotalSpaceMB,
        (( SUM(a.total_pages) * 8 ) / 1024.0)/1024.0 AS TotalSpaceGB,
        SUM(a.used_pages) * 8 AS UsedSpaceKB,
        ( SUM(a.used_pages) * 8 ) / 1024.0 AS UsedSpaceMB,
        (( SUM(a.used_pages) * 8 ) / 1024.0) /1024.0 AS UsedSpaceGB,
        ( SUM(a.total_pages) - SUM(a.used_pages) ) * 8 AS UnusedSpaceKB,
        ( ( SUM(a.total_pages) - SUM(a.used_pages) ) * 8 ) / 1024.0 AS UnusedSpaceMB,
        (( ( SUM(a.total_pages) - SUM(a.used_pages) ) * 8 ) / 1024.0)/1024.0 AS UnusedSpaceGB,
       GROUPING(t.Name)
    FROM    sys.tables t
        INNER JOIN sys.schemas s ON s.schema_id = t.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 t.is_ms_shipped = 0
        AND i.OBJECT_ID > 255
    GROUP BY s.Name,
         t.Name,
        p.Rows
       WITH ROLLUP
       ORDER BY s.Name,
        t.Name
    

    Let me know if you really need it to use sp_spaceused.

提交回复
热议问题