I am coming up with a simple query to achieve that. Firstly, we need to create a physical temporary table 'FileSpace' which will hold related information for each database. Having successfully creating the table, the following step is to execute the adequate logic, in the context of each database user via 'sp_msforeachdb', to collect file space usage which will be reported in the end. I am getting space usage information of each database file by using FILEPROPERTY system function.
Here is the whole script.
USE [master] GO CREATE TABLE [dbo].[FileSpace]( [DatabaseName] [nvarchar](128) NULL, [FileName] [sysname] NOT NULL, Type varchar(10) not null, [FileSizeGB] [decimal](10, 2) NULL, [SpaceUsedGB] [decimal](10, 1) NULL, [SpaceFreeGB] [decimal](10, 1) NULL, [SpaceFree%] [decimal](10, 1) NULL, Physical_Name varchar(max) ) ON [PRIMARY] GO EXEC sp_MSforeachdb ' USE [?] insert into master.DBO.[FileSpace]([DatabaseName] , [FileName] , Type, [FileSizeGB], [SpaceUsedGB] , [SpaceFreeGB] , [SpaceFree%],Physical_Name ) select db_name() DatabaseName, name FileName, Type_Desc , cast(size/128.0/1024.0 as decimal(10,2)) SizeGB, cast(FILEPROPERTY(name,''SpaceUsed'') /128.0/1024.0 as decimal(10,1)) SpaceUsedGB, cast((size - FILEPROPERTY(name,''SpaceUsed'') ) /128.0/1024.0 as decimal(10,1)) SpaceFreeGB, cast(((size - FILEPROPERTY(name,''SpaceUsed'') )/(size*1.0)) *100 as decimal(10,1)) [SpaceFree%], physical_name FROM sys.database_files' SELECT * FROM FileSpace WHERE [SpaceFree%]<=20 DROP TABLE FileSpace
No comments:
Post a Comment
Let me know any remarks or questions you may have. Please write down your name.