Wednesday, June 11, 2008

Get Database Tables Sizes

This script lists the database table's size. This script found under the following post:

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1784430&SiteID=1

I modified it to include the schema for table name to be useful with tables with non default schema.


DECLARE

@TotalRows int,

@Counter int,

@TableName varchar(50)


DECLARE @MyTables table


( RowID int
IDENTITY,

TableName varchar(50),


Rows
bigint,

Reserved varchar(12),

Data varchar(12),

IndexSize varchar(12),

Unused varchar(12)


)


INSERT
INTO @MyTables ( TableName )


SELECT TABLE_SCHEMA +
'.'
+ TABLE_NAME FROM
INFORMATION_SCHEMA.TABLES


SELECT @TotalRows =
@@ROWCOUNT, @Counter = 1


WHILE
( @Counter <= @TotalRows )


BEGIN


SELECT @TableName = TableName FROM @MyTables


WHERE RowID = @Counter


INSERT
INTO @MyTables EXECUTE
sp_spaceused @TableName


SET @Counter =
( @Counter + 1 )


END


DELETE
FROM @MyTables


WHERE RowID <= @TotalRows


SELECT TableName,
Rows, Reserved,Data, IndexSize, Unused FROM @MyTables


ORDER
BY Rows DESC

GO