开发者

Get overall sum of all databases size in a SQL Server

开发者 https://www.devze.com 2023-03-29 12:53 出处:网络
I want to calculate how much space my databases are using in a server. I could use sp_spacefiles or query sys.databases table but that would give me separate results for each database and I would have

I want to calculate how much space my databases are using in a server. I could use sp_spacefiles or query sys.databases table but that would give me separate results for each database and I would have to copy that into an excel sheet and calculat开发者_如何学编程e the sum from there.

Is there a direct way of doing it in T-SQL?

Thanks.


You can query master.sys.master_files:

SELECT CONVERT(DECIMAL(10,2),(SUM(size * 8.00) / 1024.00 / 1024.00)) As UsedSpace
FROM master.sys.master_files

This will give you a total in GB.

Sys.Master_files is a server-wide view that lists every file in every DB. It's available from SQL Server 2005 onward.


Here's an answer I found on SQLServerCentral.com. There are a couple different scripts provided by different users on this page.. Perhaps one of them would provide what you're looking for.

http://www.sqlservercentral.com/Forums/Topic670489-146-1.aspx

Here is one of the scripts from MANU-J:

Create TABLE #db_file_information( 
fileid integer
, theFileGroup integer
, Total_Extents integer
, Used_Extents integer
, db varchar(30)
, file_Path_name varchar(300))

-- Get the size of the datafiles

insert into #db_file_information 
( fileid 
, theFileGroup 
, Total_Extents 
, Used_Extents 
, db 
, file_Path_name )
exec sp_MSForEachDB 'Use ?; DBCC showfilestats'

-- add two columns to the temp table

alter table #db_file_information add PercentFree as 
((Total_Extents-Used_Extents)*100/(Total_extents))

alter table #db_file_information add TotalSpace_MB as 
((Total_Extents*64)/1024)

alter table #db_file_information add UsedSpace_MB as 
((Used_Extents*64)/1024)

alter table #db_file_information add FreeSpace_MB as 
((Total_Extents*64)/1024-(Used_Extents*64)/1024)

select * from #db_file_information

drop table #db_file_information


Just in case someone needs per-file calculation:

select physical_name, size,
    CONVERT(DECIMAL(10,2),(size * 8.00) / 1024.00) As UsedSpace
from master.sys.master_files
order by physical_name

The results are in MBytes

0

精彩评论

暂无评论...
验证码 换一张
取 消