从sys.database_files返回数据库名称

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从sys.database_files返回数据库名称相关的知识,希望对你有一定的参考价值。

有谁知道如何返回数据库名称?我似乎无法弄清楚如何将sys.database_files加入sys.databases

SELECT
    a.NAME as FileName,
    FG.name as FileGroup,
    a.physical_name as FilePath,
    a.type_desc as FileType,
    CONVERT(DECIMAL(12,2),ROUND(a.size/128.000,2)) AS [Size],
    CONVERT(DECIMAL(12,2),ROUND(FILEPROPERTY(a.name,'SpaceUsed')/128.000,2)) AS [Used] ,
    CONVERT(DECIMAL(12,2),ROUND((a.size-FILEPROPERTY(a.name,'SpaceUsed'))/128.000,2)) AS [Free]
FROM 
    sys.database_files a
LEFT JOIN sys.filegroups FG ON 
    FG.data_space_id = a.data_space_id
答案

使用sys.master_files代替 - 有database_id - 像这样:

select 
    a.NAME as FileName,
    FG.name as FileGroup,
    a.physical_name as FilePath,
    a.type_desc as FileType,
    CONVERT(DECIMAL(12,2),ROUND(a.size/128.000,2)) AS [Size],
    CONVERT(DECIMAL(12,2),ROUND(FILEPROPERTY(a.name,'SpaceUsed')/128.000,2)) AS [Used] ,
    CONVERT(DECIMAL(12,2),ROUND((a.size-FILEPROPERTY(a.name,'SpaceUsed'))/128.000,2)) AS [Free]
from sys.master_files a
LEFT JOIN sys.filegroups FG ON 
    FG.data_space_id = a.data_space_id;

编辑: 要向查询添加数据库名称:

select 
    d.name as DatabaseName,
    a.name as FileName,
    FG.name as FileGroup,
    a.physical_name as FilePath,
    a.type_desc as FileType,
    CONVERT(DECIMAL(12,2),ROUND(a.size/128.000,2)) AS [Size],
    CONVERT(DECIMAL(12,2),ROUND(FILEPROPERTY(a.name,'SpaceUsed')/128.000,2)) AS [Used] ,
    CONVERT(DECIMAL(12,2),ROUND((a.size-FILEPROPERTY(a.name,'SpaceUsed'))/128.000,2)) AS [Free]
from sys.databases d
left join sys.master_files a on d.database_id = a.database_id
left join sys.filegroups FG on
    FG.data_space_id = a.data_space_id;
另一答案
SELECT a.NAME as FileName ,b.name as FileGroup , b.physical_name as FilePath,   b.type_desc as FileType,
CONVERT(DECIMAL(12,2),ROUND(b.size/128.000,2)) AS [Size],
CONVERT(DECIMAL(12,2),ROUND(FILEPROPERTY(b.name,'SpaceUsed')/128.000,2)) AS [Used] ,
CONVERT(DECIMAL(12,2),ROUND((b.size-FILEPROPERTY(b.name,'SpaceUsed'))/128.000,2)) AS [Free]
FROM Sys.databases a 
INNER JOIN  Sys.master_files b ON a.database_id=b.database_id
WHERE a.database_id >4

以上是关于从sys.database_files返回数据库名称的主要内容,如果未能解决你的问题,请参考以下文章

SQL SERVER 查看数据库信息

SQL Server2008清除数据库日志

Sql Server 2008收缩日志语句

分区表测试

从主机名中提取域名

Delphi:使用元数据从 MySQL 返回数据库名称