sql-server – 查询报告磁盘空间分配和已用空间的查询

我们总共使用6个数据库作为应用程序,我们只能在所有6个自动增长数据库中共享4TB空间(通过SAN存储).

我想为单个数据库编写一个查询(报告),指示任务>下的“当前分配的空间”和“可用空闲空间”属性.收缩> SQL Server Management Studio中的数据库选项.

然后,我想将这些数字转换为TB并将每个数据库的总数转换为粗略估计我们剩余的空间.可以通过T-SQL查询访问这些字段吗?如果是这样,查询会是什么样子?

最佳答案
以下是Management Studio用于填充这些数字的查询:

SELECT
(SELECT SUM(CAST(df.size as float)) FROM sys.database_files AS df 
   WHERE df.type in ( 0, 2, 4 ) ) AS [DbSize],
SUM(a.total_pages) AS [SpaceUsed],
(SELECT SUM(CAST(df.size as float)) FROM sys.database_files AS df 
   WHERE df.type in (1, 3)) AS [LogSize]
FROM
sys.partitions p join sys.allocation_units a 
  on p.partition_id = a.container_id 
left join sys.internal_tables it 
  on p.object_id = it.object_id

您需要像Management Studio一样执行数学运算,以获得相同的数字.此外,对sys.internal_tables的左连接充其量也是多余的.因此,调整该查询以匹配您的理想输出:

SELECT
(SELECT CONVERT(DECIMAL(18,2), SUM(CAST(df.size as float))*8/1024.0)
   FROM sys.database_files AS df 
   WHERE df.type in ( 0, 2, 4 ) ) AS [DbSize],
CONVERT(DECIMAL(18,2), SUM(a.total_pages)*8/1024.0) AS [SpaceUsed],
(SELECT CONVERT(DECIMAL(18,2), SUM(CAST(df.size as float))*8/1024.0)
   FROM sys.database_files AS df 
   WHERE df.type in (1, 3)) AS [LogSize]
FROM sys.partitions p join sys.allocation_units a 
  on p.partition_id = a.container_id;

通过此更新,假设您的数据库在此期间没有更改,它应该产生:

753475.94    744030.07    2900.00

做一些简单的数学运算,并只隔离你想要的三个数字:

;WITH t(s) AS
(
  SELECT CONVERT(DECIMAL(18,2), SUM(size)*8/1024.0)
   FROM sys.database_files
   WHERE [type] % 2 = 0
), 
d(s) AS
(
  SELECT CONVERT(DECIMAL(18,2), SUM(total_pages)*8/1024.0)
   FROM sys.partitions AS p
   INNER JOIN sys.allocation_units AS a 
   ON p.[partition_id] = a.container_id
)
SELECT 
  Allocated_Space = t.s, 
  Available_Space = t.s - d.s,
  [Available_%] = CONVERT(DECIMAL(5,2), (t.s - d.s)*100.0/t.s)
FROM t CROSS APPLY d;

转载注明原文:sql-server – 查询报告磁盘空间分配和已用空间的查询 - 代码日志