Thursday, July 7, 2011

SHRINK DATABASE & SHRINK FILE

While working with huge data and large tables there are times when you get your database and log files expand ridiculously and eat up the entire disks.
This happens when you are either:
- on OLTP environment and doing lots of DMLs (INSERTS, UPDATES or DELETES) or
- on OLAP environment when you are running huge SQL queries that goes on expanding your tempdb and finally eats up your drive space.
There are lot of ways to better configure your disks and databases there to avoid such situations. But situations come and you have to approach the DBA and become a DBA yourself.
Check the LOG Size and Space used, here:
1DBCC SQLPERF (LOGSPACE)
Check if your database has adequate space available to free up:
1SELECT name ,size/128.0 - CAST(FILEPROPERTY(name'SpaceUsed'AS int)/128.0 ASAvailableSpaceInMB
2FROM sys.database_files;
Before shrinking the log file, it better to backup your transaction logs, as shown below:
1BACKUP LOG <database_name> WITH TRUNCATE_ONLY
2DBCC SHRINKFILE(database_name_log, 2)
tempdb can be freed up by simply restarting SQL Server. When SQL Server shuts down it deletes the tempdb and on restart it automatically creates tempdb database. Thus you get fresh tempdb with minimal space. This is not advisable on production servers and should be handled by experts.
Check this KB article for backing up the transaction logs and shrinking the database 

No comments: