--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
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 = 'ROWS'  --mdf
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),0)) as [free_mb]
, convert(bigint, round(((b.total_bytes / 1024.0)/1024.0),0)) as [total_mb]
, convert(bigint, round((((b.total_bytes - b.available_bytes) / 1024.0)/1024.0),0)) as [used_mb]
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  

RETURN

SELECT * 
FROM sys.master_files F WITH(NOWAIT)
WHERE f.[physical_name] LIKE 'f:%'



/* 
--craft data files shrink without reorganizing
SELECT 
    d.[name]
    ,f.[physical_name]
    ,f.[name]
    ,'USE '+d.name+';
DBCC SHRINKFILE (N'''+f.[name]+''' , 0, TRUNCATEONLY);
GO

' AS shrinkData
FROM sys.master_files F 
    JOIN sys.databases d ON d.[database_id] = f.[database_id]
WHERE f.type_desc = 'ROWS'  --mdf
AND d.[is_read_only] = 0
AND d.[is_auto_shrink_on] = 0
AND d.name NOT IN (
    'master'
    ,'tempdb'
    ,'model'
    ,'msdb'
)
*/