SQL Server - Determine Table Sizes via T/SQL

by Ashley Allen Email

If you're troubleshooting issues on SQL Server, you may find the following script useful. It will list all of the tables in a given database, giving their size, allocated space, index space, unused space, and a row count... Hope it helps you out!

USE {your_database_name}

SET NOCOUNT ON

CREATE TABLE #TBLSize
(Tblname varchar(80),
TblRows int,
TblReserved varchar(80),
TblData varchar(80),
TblIndex_Size varchar(80),
TblUnused varchar(80))

DECLARE @DBname varchar(80)
DECLARE @tablename varchar(80)

SELECT @DBname = DB_NAME(DB_ID())
PRINT 'User Table size Report for (Server / Database): ' + @@ServerName + ' / ' + @DBName
PRINT ''
PRINT 'By Size Descending'
DECLARE TblName_cursor CURSOR FOR
SELECT NAME
FROM sysobjects
WHERE xType = 'U'

OPEN TblName_cursor

FETCH NEXT FROM TblName_cursor
INTO @tablename

WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO #tblSize(Tblname, TblRows, TblReserved, TblData, TblIndex_Size, TblUnused)
EXEC Sp_SpaceUsed @tablename

-- Get the next author.
FETCH NEXT FROM TblName_cursor
INTO @tablename
END

CLOSE TblName_cursor
DEALLOCATE TblName_cursor

SELECT Tblname 'Table',
TblRows 'Row Count',
TblReserved 'Total Space (KB)',
TblData 'Data Space',
TblIndex_Size 'Index Space',
TblUnused 'Unused Space'
FROM #tblSize
Order by 'Table'


DROP TABLE #TblSize