【发布时间】:2011-08-19 13:19:06
【问题描述】:
我想计算我的数据库在服务器中使用了多少空间。我可以使用 sp_spacefiles 或查询 sys.databases 表,但这会给每个数据库单独的结果,我必须将其复制到 Excel 表中并从那里计算总和。
在 T-SQL 中有直接的方法吗?
谢谢。
【问题讨论】:
标签: sql sql-server database tsql
我想计算我的数据库在服务器中使用了多少空间。我可以使用 sp_spacefiles 或查询 sys.databases 表,但这会给每个数据库单独的结果,我必须将其复制到 Excel 表中并从那里计算总和。
在 T-SQL 中有直接的方法吗?
谢谢。
【问题讨论】:
标签: sql sql-server database tsql
您可以查询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 开始提供。
【讨论】:
这是我在 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
【讨论】:
以防万一有人需要按文件计算:
select physical_name, size,
CONVERT(DECIMAL(10,2),(size * 8.00) / 1024.00) As UsedSpace
from master.sys.master_files
order by physical_name
结果以 MBytes 为单位
【讨论】: