mssql sqlserver 使用sql脚本获取指定数据库下所有数据表的大小及数据行数的方法分享


摘要:
下文讲述基于系统表获取指定数据库下数据表的大小及行数的方法分享,如下所示:
实验环境:sql server 2008 R2



实现思路:
基于sys.tables、 sys.partitions、sys.allocation_units系统表获取数据行及数据大小的方法

USE [DataBaseName] ---待获取数据行的数据库
GO 
SELECT 
    s.Name AS [架构名], 
    t.Name AS [数据表名称], 
    p.rows AS [数据行大小], 
     CAST(ROUND((SUM(a.used_pages) / 128.00), 2) AS NUMERIC(36, 2)) AS [已使用MB], 
     CAST(ROUND((SUM(a.total_pages) - SUM(a.used_pages)) / 128.00, 2) AS NUMERIC(36, 2)) AS [未使用MB], 
     CAST(ROUND((SUM(a.total_pages) / 128.00), 2) AS NUMERIC(36, 2)) AS [总MB] 
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 
   INNER JOIN sys.schemas s ON t.schema_id = s.schema_id 
    GROUP BY t.Name, s.Name, p.Rows 
   ORDER BY s.Name, t.Name 
GO