How to list the size of the tables within your SQL Server database

Here is a useful post by Mitchel Sellers that lists information about each of the tables within a specific database. The output lists the total number of rows, reserved data size, used data size, index size, and unused space in each table.

http://www.mitchelsellers.com/blogs/articletype/articleview/articleid/121/determing-sql-server-table-size.aspx
This is very useful when performing maintenance such as data purges for size management or row analysis for performance improvements.
 
He wrote this as a stored procedure but if you leave the top two lines off the SQL you can run it from within SQL Server Management Studio (or Query Analyzer) as desired without saving it as a stored procedure - though you might find it useful enough to store to run as needed in the future.
 
Here is the SQL he wrote, without the top two lines, that you can copy/paste and run:
 

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
blog comments powered by Disqus
Tagged as: