Created
January 13, 2025 21:54
-
-
Save petesql/2bd8cc1f2932b00f9c417b54c755d555 to your computer and use it in GitHub Desktop.
Get Database Files Sizes and Free Space
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Create temp table for storing database size information | |
DECLARE @command NVARCHAR(MAX); | |
DROP TABLE IF EXISTS #MSSQL_Database_Sizes; | |
CREATE TABLE #MSSQL_Database_Sizes ( | |
[database_name] NVARCHAR(MAX) NULL, | |
current_size_mb INT NULL, | |
freespace_mb INT NULL, | |
collection_date DATE NULL | |
); | |
-- Command to gather database file size and free space information | |
SELECT @command = | |
'USE ? | |
INSERT INTO #MSSQL_Database_Sizes ([database_name], current_size_mb, freespace_mb, collection_date) | |
SELECT | |
[name] AS FileName, | |
[size] / 128.0 AS current_size_mb, | |
[size] / 128.0 - CAST(FILEPROPERTY([name], ''SpaceUsed'') AS INT) / 128.0 AS freespace_mb, | |
CAST(GETDATE() AS DATE) AS collection_date | |
FROM sys.database_files'; | |
-- Execute command for all databases | |
EXEC sp_MSforeachdb @command; | |
-- Display results | |
SELECT * | |
FROM #MSSQL_Database_Sizes | |
ORDER BY current_size_mb DESC; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment