--databases space
IF OBJECT_ID('tempdb..#dbs')IS NOT NULL BEGIN;
	DROP TABLE #dbs;
END;

CREATE TABLE #dbs ( [database_name] NVARCHAR(128), [log_size_mb] DECIMAL(18,2), [row_size_mb] DECIMAL(18,2), [total_size_mb] DECIMAL(18,2) )

INSERT INTO [#dbs] ([database_name], [log_size_mb], [row_size_mb], [total_size_mb])
SELECT 
      database_name = DB_NAME(database_id)
    , log_size_mb = CAST(SUM(CASE WHEN f.type_desc = 'LOG' THEN size END) * 8. / 1024 AS DECIMAL(18,2))
    , row_size_mb = CAST(SUM(CASE WHEN type_desc = 'ROWS' THEN size END) * 8. / 1024 AS DECIMAL(18,2))
    , total_size_mb = CAST(SUM(size) * 8. / 1024 AS DECIMAL(18,2))
FROM sys.master_files F WITH(NOWAIT)
GROUP BY F.database_id
ORDER BY [total_size_mb] DESC 

SELECT 
    d.[name] AS dbName
    ,f.[physical_name] AS physicalFileName
    ,f.[name] AS logicalFileName
    --,d2.[log_size_mb]
    --,d2.[row_size_mb]
    ,CAST(f.size * 8. / 1024 AS DECIMAL(18,2)) AS fileSizeMB
    ,d2.[total_size_mb] AS totalDbSizeMB
    ,'USE '+d.name+';
DBCC SHRINKFILE (N'''+f.[name]+''' , 0, TRUNCATEONLY);
GO

' AS shrinkData
,'USE '+d.name+';
DBCC SHRINKFILE (N'''+f.[name]+''' , 1024);
GO

' AS reorganizeData
FROM sys.master_files F 
    JOIN sys.databases d ON d.[database_id] = f.[database_id]
    JOIN [#dbs] [d2] ON d2.[database_name] = d.[name]
WHERE f.type_desc IN (
    'ROWS'  --mdf
    --,'LOG'
)
--AND f.[physical_name] LIKE 'f%'
--AND d.[is_read_only] = 0
--AND d.[is_auto_shrink_on] = 0
--AND d.name NOT IN (
--    'master'
--    ,'tempdb'
--    ,'model'
--    ,'msdb'
--)
ORDER BY [d2].[row_size_mb] DESC, d.name DESC, f.name ASC ;

--free disk space
SELECT       DISTINCT 
        CONVERT(VARCHAR(512), [b].[volume_mount_point]) AS [volume_mount_point],
        CONVERT(VARCHAR(512), [b].[logical_volume_name]) AS [logical_volume_name],
        CONVERT(
            DECIMAL(18, 1),
            ROUND(((CONVERT(FLOAT, [b].[available_bytes]) / CONVERT(FLOAT, [b].[total_bytes])) * 100), 1)) AS [percent_free],
        CONVERT(BIGINT, ROUND((([b].[available_bytes] / 1024.0) / 1024.0 / 1024.0), 0)) AS [free_gb],
        CONVERT(BIGINT, ROUND((([b].[available_bytes] / 1024.0) / 1024.0 ), 0)) AS [free_mb],
        CONVERT(BIGINT, ROUND((([b].[total_bytes] / 1024.0) / 1024.0 / 1024.0), 0)) AS [total_gb],
        CONVERT(BIGINT, ROUND(((([b].[total_bytes] - [b].[available_bytes]) / 1024.0) / 1024.0 / 1024.0), 0)) AS [used_gb],
        CONVERT(BIGINT, ROUND((([b].[total_bytes] / 1024.0) / 1024.0), 0)) / 100 * 5 / 1024.0 AS [5% space in Go is],
        CONVERT(BIGINT, ROUND((([b].[total_bytes] / 1024.0) / 1024.0), 0)) / 100 * 10 / 1024.0 AS [10% space in Go is],
        CONVERT(BIGINT, ROUND((([b].[total_bytes] / 1024.0) / 1024.0), 0)) / 100 * 15 / 1024.0 AS [15% space in Go is],
        CURRENT_TIMESTAMP AS now,
        REPLACE(@@SERVERNAME, '\apssql', '') AS srvName
  FROM       sys.master_files AS [a]
 CROSS APPLY sys.dm_os_volume_stats(a.database_id, a.[file_id]) AS [b]
 ORDER BY [percent_free] ASC;
