【问题标题】:Get overall sum of all databases size in a SQL Server获取 SQL Server 中所有数据库大小的总和
【发布时间】:2011-08-19 13:19:06
【问题描述】:

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

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

谢谢。

【问题讨论】:

    标签: sql sql-server database tsql


    【解决方案1】:

    您可以查询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 开始提供。

    【讨论】:

    • 这正是我想要的,谢谢。我想对于 SQL Server 2000,我将不得不使用 @jennifer-s 提供的代码,对吧?
    • 谢谢。简单实用。
    【解决方案2】:

    这是我在 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
    

    【讨论】:

    • 我们通常不鼓励仅链接的答案,因为如果链接失效,答案将毫无用处。请在您的答案正文中摘录或一些示例。
    • 对不起。编辑以包含其中一个脚本。
    • 请注意sp_MSforeachdb;它并不总是适用于所有数据库(请参阅我的 cmets sqlblog.com/blogs/aaron_bertrand/archive/2010/12/29/…)。我写了一个替换,欢迎从这里复制:mssqltips.com/tip.asp?tip=2201
    【解决方案3】:

    以防万一有人需要按文件计算:

    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 为单位

    【讨论】:

      猜你喜欢
      • 2018-09-15
      • 1970-01-01
      • 2011-12-15
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 1970-01-01
      • 2019-08-03
      • 2020-06-29
      相关资源
      最近更新 更多