欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

参考sql2012存储过程写的统计所有用户表尺寸大小的示例

程序员文章站 2023-11-04 20:17:34
可以结合sp_msforeachdb再遍历所有用户数据库查看所有表的尺寸大小,注意它的参数@sql不能超过nvarchar(2000),这里就不贴出代码了。另外还可以定期运...

可以结合sp_msforeachdb再遍历所有用户数据库查看所有表的尺寸大小,注意它的参数@sql不能超过nvarchar(2000),这里就不贴出代码了。
另外还可以定期运行并将结果保存下来,以便观察数据变化趋势。

查询单个数据库的所有用户表尺寸大小:

复制代码 代码如下:

select @@servername as servername,db_name() as dbname ,object_id as objectid, schema_name(schema_id) as schname, name as tablename
    ,rowcnt as rows,columns,indexes,rowlength
    ,reservedkb, tableusedkb
    ,usedkb-tableusedkb as indexusedkb,reservedkb-usedkb as unusedkb
    ,create_date as createdate,modify_date as lastmodifieddate, getutcdate() as trackingutctime
from
(select
    object_id
    ,schema_id
    ,name
    ,(select max(row_count) from sys.dm_db_partition_stats p with(nolock) where p.object_id=t.object_id and p.index_id < 2)  as rowcnt
    ,(select count(1) from dbo.syscolumns with(nolock) where id = t.object_id) as columns
    ,(select count(distinct index_id) from sys.dm_db_partition_stats p with(nolock) where p.object_id=t.object_id) as indexes
    ,(select sum(length) from dbo.syscolumns with(nolock) where id = t.object_id) as rowlength
    ,isnull((select sum(reserved_page_count) from sys.dm_db_partition_stats p with(nolock) where p.object_id=t.object_id),0)*8
        + isnull((select sum(reserved_page_count)
                from sys.dm_db_partition_stats p2 with(nolock)
                inner join sys.internal_tables it with(nolock) on p2.object_id = it.object_id
                where it.parent_id = t.object_id
                        and it.internal_type in (202,204,207,211,212,213,214,215,216,221,222,236)),0)* 8 as reservedkb
    ,isnull((select sum(in_row_data_page_count + lob_used_page_count + row_overflow_used_page_count)
                 from sys.dm_db_partition_stats p with(nolock) where p.object_id=t.object_id and p.index_id < 2),0)* 8 as tableusedkb
    ,isnull((select sum(used_page_count) from sys.dm_db_partition_stats p with(nolock) where p.object_id=t.object_id),0)*8
        + isnull((select sum(used_page_count)
                from sys.dm_db_partition_stats p2 with(nolock)
                inner join sys.internal_tables it with(nolock) on p2.object_id = it.object_id
                where it.parent_id = t.object_id
                        and it.internal_type in (202,204,207,211,212,213,214,215,216,221,222,236)),0)* 8 as usedkb
    ,create_date
    ,modify_date
from sys.tables t with(nolock)
where type='u'
) a
order by reservedkb desc