在SQL Server中获取所有数据库大小的总和

问题描述:

我想计算我的数据库在服务器中使用了多少空间。我可以使用sp_spacefiles或查询sys.databases表,但这会给我每个数据库单独的结果,我将不得不复制到Excel表并从那里计算总和。在SQL Server中获取所有数据库大小的总和

在T-SQL中有直接的方法吗?

谢谢。

您可以查询master.sys.master_files

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

这会给你在GB总。

Sys.Master_files是一个服务器范围的视图,列出每个数据库中的每个文件。它可从SQL Server 2005开始使用。

+0

这正是我所期待的,谢谢。我猜想对于SQL Server 2000,我将不得不使用@ jennifer-s提供的代码,对吧? – olmed0

+0

谢谢。简单而有用。 –

下面是我在SQLServerCentral.com上找到的答案。在这个页面上有不同的用户提供了几个不同的脚本..也许其中一个会提供你正在寻找的东西。

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

这里是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 
+0

我们一般不鼓励链路只有答案,因为如果链接死亡的回答是没用的。请在答案的文字中加上一段摘录或一些例子。 – JNK

+0

对不起。编辑包含其中一个脚本。 –

+1

请注意sp_MSforeachdb;它并不总是为所有数据库运行(请参阅我对此的评论http://sqlblog.com/blogs/aaron_bertrand/archive/2010/12/29/a-more-reliable-and-more-flexible-sp-msforeachdb的.aspx)。我写了一个替代品,欢迎您从这里复制:http://www.mssqltips.com/tip.asp?tip=2201 –

万一有人需要每个文件计算:

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

结果是兆字节