I've written the following script to get the size, usedSpace and freeSpace of my databases. However, the results don't always match what SQL Management Studio (2005) shows. I'm sure I'm not taking something into account and any help would be appreciated.
if object_id('[tempdb].[dbo].[#databaseStats]') is null
create table #databaseStats (dbName varchar(50), TotalSizeMB decimal(15,2), SpaceUsedMB decimal(15,2), FreeSpaceMB decimal(15,2), FileName varchar(100))
else
truncate table #databaseStats;
exec sp_msforeachdb
'use [?];
insert #databaseStats
select
db_name(),
round(convert( decimal(10,2), size) * 8192.0/1048576.0, 2) as TotalSizeMB,
round(convert(decimal(10,2), fileproperty(name,''SpaceUsed'')) * 8192.0/1048576.0, 2) as SpaceUsedMB,
round(convert( decimal(10,2), size) * 8192.0/1048576.0 - convert(decimal(10,2), fileproperty(name,''SpaceUsed'')) * 8192.0/1048576.0, 2) as FreeSpaceMB,
name
from sys.sysfiles;'
select * from #databaseStats order by dbName;
select dbName, sum(TotalSizeMB) AS Size, sum(SpaceUsedMB) as Used, sum(FreeSpaceMB) as SpaceAvailable from #databaseStats group by dbName;
Thanks
if object_id('[tempdb].[dbo].[#databaseStats]') is null
create table #databaseStats (dbName varchar(50), TotalSizeMB decimal(15,2), SpaceUsedMB decimal(15,2), FreeSpaceMB decimal(15,2), FileName varchar(100))
else
truncate table #databaseStats;
exec sp_msforeachdb
'use [?];
insert #databaseStats
select
db_name(),
round(convert( decimal(10,2), size) * 8192.0/1048576.0, 2) as TotalSizeMB,
round(convert(decimal(10,2), fileproperty(name,''SpaceUsed'')) * 8192.0/1048576.0, 2) as SpaceUsedMB,
round(convert( decimal(10,2), size) * 8192.0/1048576.0 - convert(decimal(10,2), fileproperty(name,''SpaceUsed'')) * 8192.0/1048576.0, 2) as FreeSpaceMB,
name
from sys.sysfiles;'
select * from #databaseStats order by dbName;
select dbName, sum(TotalSizeMB) AS Size, sum(SpaceUsedMB) as Used, sum(FreeSpaceMB) as SpaceAvailable from #databaseStats group by dbName;
Thanks