Calculate the physical size of a SQL Server database table (data and indexes) , if rows exist . These steps present a good estimate
1) Use sp_spaceused ‘myTableName’.
2) To maintain up to date data, use DBCC UPDATEUSAGE before the sp_spaceused
For a specific table :
DBCC UPDATEUSAGE(‘<DB_NAME>’,‘<TABLE_NAME>’)
Or all the tables in the current database :
DBCC UPDATEUSAGE(0);
3) The alternative is to execute sp_spaceused ‘myTableName’,0
4) To calculate the sum of table data size , use a method to calculate and add for all tables. Don’t rely on database_size, as it includes the log files.
How does sp_spaceused work?
1) Checks to see if user wants usages updated
2) Checks to see object exists
3) Updates usage if user specified
4) Returns reserved, used pages,index size and unused
Snippet of code from stored procedure:
SELECT name = OBJECT_NAME (@id), rows = convert (char(11), @rowCount), reserved = LTRIM (STR (@reservedpages * 8, 15, 0) + ' KB'), data = LTRIM (STR (@pages * 8, 15, 0) + ' KB'), index_size = LTRIM (STR ((CASE WHEN @usedpages > @pages THEN (@usedpages - @pages) ELSE 0 END) * 8, 15, 0) + ' KB'), unused = LTRIM (STR ((CASE WHEN @reservedpages > @usedpages THEN (@reservedpages - @usedpages) ELSE 0 END) * 8, 15, 0) + ' KB')
Author: Jack Vamvas (http://www.sqlserver-dba.com)