Sql-server – How to reclaim the unused Space in a database

sql serversql-server-2005

The database is almost of size 55GB. This database should have never grown to this size as some of the maintenance jobs were not running.

I have deleted almost 30GB of data. Now the database size is almost 45GB and Space Available is almost 20GB .

Which shows that Actual size of the database is now almost 25GB and there is some Unused space that needs to be returned to Operating System.

I have executed DBCC commands for both Database and individual files (8 of them). And I only managed to release a couple of GBs.

The Commands I used are as follows

DBCC SHRINKDATABASE (N'MyDB');
GO

DBCC SHRINKFILE('Filename1', 0 , TRUNCATEONLY)
GO
DBCC SHRINKFILE('Filename2', 0 , TRUNCATEONLY)
GO
  and so on....

But this seems to have no affect on database size and the available space.

I read an article which suggested rebuilding indexes and then shrinking database will solve this issue.

But once I have shrunk the database I would have to rebuild indexes anyway as shrinking database would have made a mess of indexes.

My requirement is to only leave 10% space for db to grow and release the unused space. Then I plan to rebuild Indexes and update statistics after that.

What would be the best approach to this problem. Any suggestions or pointers in the right direction are much appreciated.

Thank you in advance

Best Answer

Is there a particular reason you are specifying TRUNCATEONLY? As per the documentation on DBCC SHRINKFILE:

TRUNCATEONLY

Releases all free space at the end of the file to the operating system but does not perform any page movement inside the file. The data file is shrunk only to the last allocated extent.

target_size is ignored if specified with TRUNCATEONLY.

If that is not the intended behavior you were looking for (which it doesn't sound like it is), then you could try without that option set.

Also, there are other factors that hinder database file shrinking as well, such as text`ntext\image` BLOB data. So it is worth looking into the possibility of the existence of data with these data types.