Recently I come across the need to shrink the database file to avoid the file system being filling up.
The first thoughts come to the mind is using DBCC SHRINKFILE
DBCC SHRINKFILE with TRUNCATEONLY option only remove the free pages after the last allocate extend. It does not perform any page moving movement. Hence it is generally no harm and perform very quick.
If that is not enough, we can use DBCC SHRINKFILE(FILENAME,TARGETSIZE).
This will perform the page movement and it will be slower and take much longer time. This may possible shrink the file smaller then its initialize size as long as there is free space within the file.
To check the free space within the file, we can run
This information is different from what you get from sp_spaceused. sp_spaceused is given you the total size combine with log and data. the sys.database file is break down by each database file.
The DBCC SHRINKFILE process can be stop at any time. Any work has been complete will retain.
In many case, you may wonder how long does it take to complete,we can query from sys.dm_exec_requests
DBCC Shrinkfile does not retain the index fragmentation and could possible make it worse. It is suggest to check the index fragmentation after you shrink the file and decide whether it is need to rebuild or recognize.
Below query can be used to check the index fragmentation on the given database and given file group.