Display the size of all tables in Sql Server 2005

本文介绍两种查询SQL Server中所有表所占用空间的方法:一种是通过循环遍历所有表名并调用sp_spaceused过程;另一种是利用未公开的sp_MSforeachtable过程直接查询。

sp_spaceused returns number of rows, disk space reserved, and disk space used by a table. However when you have to return the space used by all the tables in a database, you have two options: One is to loop through all the tables and then pass the table name to the sp_spaceused procedure. The second is to use the undocumented sp_MSforeachtable procedure. We will explore both of these over here:

The Lengthy Way

USE  yourdbname
DECLARE   @TblNames   Table
(
COUNTER 
INT   IDENTITY ( 1 , 1 ),
tbl_name 
nvarchar ( 100 NULL
)
DECLARE   @ROWCOUNT   INT
DECLARE   @I   INT
DECLARE   @str   nvarchar ( 100 )
SET   @I   =   1
INSERT   INTO   @TblNames (tbl_name)  SELECT  name  FROM  sys.Tables
SET   @ROWCOUNT   =   @@ROWCOUNT
WHILE   @I   <=   @ROWCOUNT
BEGIN
SELECT   @str   =  tbl_name  FROM   @TblNames   WHERE  COUNTER  =   @I
EXEC  sp_spaceused  @str
SET   @I   =   @I   + 1
END

 

Note: The advantage in taking the lengthy approach is that you can create another temporary table and sort the tables based on the space used.

The Short Way
USE  yourdbname
EXEC  sp_MSforeachtable  @command1 = " EXEC  sp_spaceused  ' ? ' "

Note: sp_MSforeachtable is an undocumented stored procedure

References :
http://msdn2.microsoft.com/en-us/library/ms188776.aspx
http://www.msnewsgroups.net/group/microsoft.public.dotnet.languages.csharp/topic37975.aspx
http://www.mssqlcity.com/Articles/Undoc/SQL2000UndocSP.htm

转载于:https://www.cnblogs.com/josephshi/archive/2008/04/02/1134564.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值