Thursday, December 30, 2010

How To Get/Retrieve Size Of Tables In SQL Server Databases

How To Get/Retrieve Size Of Tables In SQL Server Databases

Sometime we wonder why an application database grew so heavy during the short period of development and testing process. Here most of us wanted to know what are the actual stats of used space by each table and if we need this information without the use of Management Studio's table properties dialog, then follow this...

In fact SQL Server gives us everything we need with a Stored Procedure that is called sp_spaceused. But this SP does not support iterating over the tables in some database, so we needed to leverage another Stored Procedure sp_msForEachTable, but this is undocumented.


SET NOCOUNT ON
DBCC UPDATEUSAGE(0)

-- Get Total DB size.
EXEC sp_spaceused

-- Table row counts and their sizes.
CREATE TABLE #tempTBL
(
[nameOfTable] NVARCHAR(128),
[rowsInTable] CHAR(11),
reserved_size VARCHAR(18),
data_size VARCHAR(18),
index_size VARCHAR(18),
unused_size VARCHAR(18)
)

-- Insert into temp table
INSERT #tempTBL EXEC sp_msForEachTable 'EXEC sp_spaceused ''?'''

-- Show it to user
SELECT * FROM #tempTBL

-- Number of rows
SELECT SUM(CAST([rowsInTable] AS int)) AS [rowsInTable] FROM #tempTBL

-- Drop the temp table
DROP TABLE #tempTBL

.

1 comment:

  1. well, by accidently, I'm a young or green programmer of visual basic 6 and need a lot of source of information about how to develop and optimize my database

    ReplyDelete