Determing SQL Server Table Size

CREATE PROCEDURE GetAllTableSizesAS/*
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(id, N'IsUserTable') = 1FOR READ ONLY
--A procedure level temp table to store the resultsCREATE TABLE #TempTable
(
tableName
varchar(100),
numberofRows
varchar(100),
reservedSize
varchar(50),
dataSize
varchar(50),
indexSize
varchar(50),
unusedSize
varchar(50)
)
--Open the cursorOPEN tableCursor
--Get the first table name from the cursorFETCH NEXT FROM tableCursor INTO @TableName
--Loop until the cursor was not able to fetchWHILE (@@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 @TableNameEND
--Get rid of the cursorCLOSE tableCursorDEALLOCATE tableCursor
--Select all records so we can use the reultsSELECT * FROM #TempTable
--Final cleanup!DROP TABLE #TempTable
GO

Comments