I am attempting to programmatically monitor the size of a SQL Server database, so that my admin section of my web app can report it, and I can use that to execute some cleanup SPs, to clear log files, etc.
I use the following code to calculate the size of the tables, per SO recommendation:
CREATE TABLE #t (name SYSNAME, rows CHAR(11), reserved VARCHAR(18), data VARCHAR(18), index_size VARCHAR(18), unused VARCHAR(18))EXEC sp_msforeachtable 'INSERT INTO #t EXEC sp_spaceused ''?'''-- SELECT * FROM #t ORDER BY name-- SELECT name, CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3)) FROM #t ORDER BY nameSELECT SUM(CONVERT(INT, SUBSTRING(data, 1, LEN(data)-3))) FROM #tDROP TABLE #t
When I run this against my small sample database, I get a total sum value of ~6.8 megabytes. When I look at the properties of my database, it shows 15.5 megabytes.
I have the following questions:
1. What else can make up the difference?
2. Can this difference be described as ‘overhead’, which will only grow at a fraction of the pace as other data grows (rough estimate is all I need for this).
3. Stored Procedures, Functions, Views, Triggers are in this ‘overhead’ space? Is there a way to calculate these?
4. Is there another way to get the WHOLE database size? I really just want a simple way to get the REAL size.
The difference, in my opinion, is due to the fact that the size you see in the ‘Properties’ page is calculated by querying the table .sys.database_files, which counts the number of 8KB pages allocated by each database file.
To obtain the same result, simply run the following query (SQL Server 2005):
More information about sys.database_files on MSDN website.
Hope this helps. 🙂
Diego