mssql里sp_MSforeachtable和sp_MSforeachdb的用法

当SQLServer数据库越来越庞大,而其中的表有非常多的时候,想要知道到底是哪些表最耗存储空间,到底该怎样统计各个表的存储大小呢?其实SQLServer提供了一个sp_spaceused的系统存储过程可以实现该功能,下面就是调用的SQL:

 

create   table   #tb(表名   sysname,记录数   int  
  ,保留空间   varchar(10),使用空间   varchar(10)  
  ,索引使用空间   varchar(10),未用空间   varchar(10))  
   
  insert   into   #tb   exec   sp_MSForEachTable   'EXEC   sp_spaceused   ''?'''  
   
  select   *   from   #tb  
   
  go  
  drop   table   #tb  

这样就可以枚举出每个表存储空间的详细使用情况!

 

exec sp_Msforeachtable 'select 1 from ? where 1=2'

mssql里sp_MSforeachtable和sp_MSforeachdb的用法

mssql6.5开始微软提供了两个不公开,非常有用的系统存储过程sp_MSforeachtablesp_MSforeachdb,用于遍历某个数据库的每个表和遍历DBMS管理下的每个数据库。

我们在master数据库里执行下面的语句可以看到两个proc详细的代码

use master

exec sp_helptext sp_MSforeachtable

exec sp_helptext sp_Msforeachdb


sp_MSforeachtable系统存储过程有7个参数,解释如下:

@command1 nvarchar2000,  --第一条运行的T-SQL指令

@replacechar nchar1 = N'?',   --指定的占位符号

@command2 nvarchar2000= null,--第二条运行的T-SQL指令

@command3 nvarchar2000= null, --第三条运行的T-SQL指令

@whereand nvarchar2000= null, --可选条件来选择表

@precommand nvarchar2000= null, --在表前执行的指令

@postcommand nvarchar2000= null --在表后执行的指令 



sp_MSforeachdb
除了@whereand外,和sp_MSforeachtable的参数是一样的。



--
我们来看看sp_MSforeachtable的用法(sp_MSforeachdb的用法类似):

--统计数据库里每个表的详细情况:

exec sp_MSforeachtable @command1="sp_spaceused '?'"

 

--检查数据库里每个表或索引视图的数据、索引及textntext image 页的完整性

--下列语句需在单用户模式下执行(sp_dboption 'db_name', 'single user', 'true',true改成false就又变成多用户了

exec sp_msforeachtable "dbcc checktable('?',repair_rebuild)"

posted @ 2012-05-23 17:17  莫问前程  阅读(1130)  评论(0编辑  收藏  举报