首页 > 数据库 > SQL Server > 正文

如何获取SQL Server数据库里表的占用容量大小

2024-08-31 00:48:35
字体:
来源:转载
供稿:网友

其实只要使用系统内置的存储过程sp_spaceused就可以得到表的相关信息

如:sp_spaceused 'tablename'


以下是为了方便写的一个存储过程,目的是把当前的所有表的相关信息全部都保存在一个指定的表里面

create procedure get_tableinfo as
 
if not exists (select * from dbo.sysobjects where id = object_id(n'[dbo].[tablespaceinfo]') and objectproperty(id, n'isusertable') = 1)
create table  tablespaceinfo                         --创建结果存储表
              (nameinfo varchar(50) , 
               rowsinfo int , reserved varchar(20) , 
               datainfo varchar(20)  , 
               index_size varchar(20) , 
               unused varchar(20) )
 
 
delete from tablespaceinfo --清空数据表
 
declare @tablename varchar(255)  --表名称
 
declare @cmdsql varchar(500)
 
declare info_cursor cursor for 
select o.name  
from dbo.sysobjects o where objectproperty(o.id, n'istable') = 1 
     and o.name not like n'#%%'  order by o.name
 
open info_cursor
 
fetch next from info_cursor 
into @tablename 
 
while @@fetch_status = 0
begin
 
  if exists (select * from dbo.sysobjects where id = object_id(@tablename) and objectproperty(id, n'isusertable') = 1)
  execute sp_executesql 
         n'insert into tablespaceinfo  exec sp_spaceused @tbname',
          n'@tbname varchar(255)',
          @tbname = @tablename
 
  fetch next from info_cursor 
  into @tablename 
end
 
close info_cursor
deallocate info_cursor
go
 
 

执行存储过程
exec get_tableinfo

查询运行该存储过程后得到的结果
select *
from tablespaceinfo 
order by cast(left(ltrim(rtrim(reserved)) , len(ltrim(rtrim(reserved))

  • 本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。
  • 发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表