Determing SQL Server Table Size 

A common problem that I have recently encountered was trying to identify areas of my website database that were taking up the most physical storage space. At work I maintain a DotNetNuke installation that includes a 4.5 Gb reporting database and I was trying to pinpoint the exact sizes of ALL tables in my database and was having a few problems. I started using the "sp_spaceused" stored procedure but I had to run that for every table, I have over 200 tables in this database and it was just not feasiable for me to do it this way. Therefore I wrote a stored procedure that will perform all needed data calls and will return a result set with the data on all tables. In this post I will share the script as well as a few interesting things I learned while writing it.

Environments

This stored procedure has been tested and used on a SQL Server 2000 instance, this may or may not work successfully on other versions of SQL Server, I have not yet had the time to test.

Overview

The process that the stored procedure goes through is very simple, first we declare a cursor that will get the names of all user defined tables in the current database. Then we create a temporary table to store the individual data elements for each table. Then we loop through the created cursor and save the results of the sp_spaceused command to our temporary table. The last steps include closing and deallocating the cursor, selecting all rows from out temp table and lastly dropping that table.

When I created this procedure the one item that I found to be very intersting was the INSERT [TABLE] EXEC [SP] portion. I have used INSERT INTO [TABLE] SELECT ... type statements before where I use a query to load data, but never before had I loaded data into a table directly from the results of a stored procedure execution.

The Script

CREATE PROCEDURE GetAllTableSizes
AS
/*
    Obtains spaced used data for ALL user tables in the database
*/
DECLARE @TableName VARCHAR(100)    --For storing values in the cursor

--Cursor to get the name of all user tables from the sysobjects listing
DECLARE tableCursor CURSOR
FOR 
select 
[name]
from dbo.sysobjects 
where  OBJECTPROPERTY(idN'IsUserTable'1
FOR READ ONLY

--A procedure level temp table to store the results
CREATE TABLE #TempTable
(
    tableName 
varchar(100),
    numberofRows 
varchar(100),
    reservedSize 
varchar(50),
    dataSize 
varchar(50),
    indexSize 
varchar(50),
    unusedSize 
varchar(50)
)

--Open the cursor
OPEN tableCursor

--Get the first table name from the cursor
FETCH NEXT FROM tableCursor INTO @TableName

--Loop until the cursor was not able to fetch
WHILE (@@Fetch_Status >0)
BEGIN
    
--Dump the results of the sp_spaceused query to the temp table
    
INSERT  #TempTable
        
EXEC sp_spaceused @TableName

    
--Get the next table name
    
FETCH NEXT FROM tableCursor INTO @TableName
END

--Get rid of the cursor
CLOSE tableCursor
DEALLOCATE tableCursor

--Select all records so we can use the reults
SELECT 
FROM #TempTable

--Final cleanup!
DROP TABLE #TempTable

GO

The above is the actual stored procedure, this must be created first then you simply call this one procedure to get the list of tables and sizes. At the bottom of this article you will find a zip file available for download that will include this script file.

Usage

Now to get the table sizes for the current database you can simply run the following command.

EXEC GetAllTableSizes

The results of this procedure execution will show you the number of rows and physical sizes of each user defined table in your database.

Downloads

Click here to download a copy of the SQL Statement used to create this procedure.

Posted by Mitchel on Friday, July 27, 2007
 

Comments

Comments from the following blog entry: Determining All Table Sizes in SQL Server, located at: http://www.publicidentity.ca/post/2007/11/Determining-All-Table-Sizes-in-SQL-Server.aspx

By Public Identity on Monday, November 12, 2007 at 5:21 AM

Very Nice Workaround!! Keep up the good work!!

By John Katsiotis on Thursday, February 21, 2008 at 1:36 AM

Great tool, but I would like to see them listed by datasize with the largest on top. How would that be done? ORDER BY does not seem to work correctly.

By Justin on Friday, February 29, 2008 at 4:15 PM

Justin,

The result from SQL Server is a varchar data element. If you wanted to be able to sort it based on the sizes, when inserting the values into the temporary table, you would have to trim off the KB designator at the end of the size, and convert it to a numeric data type column. It is do-able, but you will have to modify the SQL to get it done.

if you want post a request in my Forum and I can try get a modified version of the script out there.

By mitchel.sellers@gmail.com on Saturday, March 01, 2008 at 6:03 AM

hi
there is a simple wayt to get size off table is sql sever by SP_SPACEUSED 'TABLENAME'

By bahman on Saturday, May 31, 2008 at 7:18 PM

Yes, that is the method that this uses, it just combines the info for ALL tables in your database.

By mitchel.sellers@gmail.com on Sunday, June 01, 2008 at 4:51 PM

ORDER BY CAST(LEFT(dataSize,LEN(dataSize)-3) AS NUMERIC(18,0)) DESC

By Mike M on Tuesday, June 10, 2008 at 1:39 PM

Your SP seems to be working for objects with 'dbo' owner but in the case of tables with schema name prefixed results in error. The SP has to be modified according to that.

By Bala on Thursday, July 03, 2008 at 10:49 PM

Nice one! Helped me find what was making an inherited database 16Gb big (15 Gb in a single, unnecessary, stats table!).

By Tony B on Wednesday, July 16, 2008 at 7:39 AM

Many thanks, much appreciated.

By grafeful on Tuesday, August 19, 2008 at 7:18 AM

For SQL2000 (and earlier) you should run DBCC UPDATEUSAGE to make sure you get the correct counts returned. From Books Online:
In earlier (before 2005) versions of SQL Server, the values for the table and index row counts and page counts can become incorrect. Databases that were created on versions prior to SQL Server 2005 may contain incorrect counts. Therefore, we recommend running DBCC UPDATEUSAGE after upgrading to SQL Server 2005 to correct any invalid counts.

By Patrick on Tuesday, September 23, 2008 at 2:07 PM

Yes, that is a good point, the down side, is recalculation is VERY costly if you go to run it on ALL tables inside a database at once, thus why I left that option off in this example.

By mitchel.sellers@gmail.com on Tuesday, September 23, 2008 at 4:18 PM

Superb.....Its Very helpful.

By Raghavendra Nukala on Wednesday, October 01, 2008 at 12:36 AM

I found the following very useful.

http://www.therightstuff.de/2007/11/19/How-To-Obtain-The-Size-Of-All-Tables-In-A-SQL-Server-Database.aspx

Here I can't see any screenshot to see how it works so I was a bit hesitant to use the script.

So, I used the steps from above link instead.

Anyway, thank you for your posting.

By Fiaz on Sunday, October 12, 2008 at 7:33 PM

I think the following statement would suffice

EXEC sp_MSforeachtable @command1="EXEC sp_spaceused '?'"

By sarathy on Wednesday, November 12, 2008 at 12:41 AM
Click here to post a comment

Donate

Show your appreciation for the content/modules made available by MitchelSellers.com by making a donation. Donations are used to assist with dedicating time to creating free content.