In this post, I am providing one T-SQL script which generates DBCC Shrinkfile for each database file of the SQL Server.
Generally, database administrator prefers to execute SHRINK when the database file is occupying more space and require to free unused space.
But In common practice, we should not execute SHRINK on any of SQL Server Database because it generates more fragmentation.
After SHRINK, we should execute the index rebuild or index reorganize to remove all fragmentation.
But still, I am sharing one T-SQL script which generates SHRINK script for each database file.
In one of our standby server, I require to execute SHRINK for each database so I have prepared this script.
'use ' + db_name(dbid) + char(13) + 'dbcc shrinkfile (' + quotename(sf.name,'''') + ' ,truncateonly)'
FROM sys.sysaltfiles AS sf
INNER JOIN sys.databases d
ON sf.dbid = d.database_id
WHERE d.state_desc = 'online'