Listing information about all database files in SQL Server

后端 未结 13 2129
遥遥无期
遥遥无期 2021-02-01 00:08

Is it possible to list information about the files (MDF/LDF) of all databases on an SQL Server?

I\'d like to get a list showing which database is using what files on th

13条回答
  •  天涯浪人
    2021-02-01 00:32

    just adding my 2 cents .

    if specifically looking to find total free space only in Data files or only in Log files in all the databases, we can use "data_space_id" column. 1 is for data files and 0 for log files.

    CODE:

    Create Table ##temp
    (
        DatabaseName sysname,
        Name sysname,
        spacetype sysname,
        physical_name nvarchar(500),
        size decimal (18,2),
        FreeSpace decimal (18,2)
    )   
    Exec sp_msforeachdb '
    Use [?];
    
    Insert Into ##temp (DatabaseName, Name,spacetype, physical_name, Size, FreeSpace)
        Select DB_NAME() AS [DatabaseName], Name,   ***data_space_id*** , physical_name,
        Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2) as decimal(18,2))/1024 as nvarchar) SizeGB,
        Cast(Cast(Round(cast(size as decimal) * 8.0/1024.0,2)/1024 as decimal(18,2)) -
            Cast(FILEPROPERTY(name, ''SpaceUsed'') * 8.0/1024.0 as decimal(18,2))/1024 as nvarchar) As FreeSpaceGB
        From sys.database_files'
    
    
    select  
        databasename
        , sum(##temp.FreeSpace) 
    from 
        ##temp 
    where 
        ##temp.spacetype = 1  
    group by 
        DatabaseName
    
    drop table ##temp 
    
    

提交回复
热议问题