Wednesday 7 October 2015

Log Shrinking as part of a Maintenance task SQL server

If you are going to be shrinking a log file using this method you should have the database in simple recovery mode. Transaction log backups will no longer be required to shrink the log file but not having them will impact disaster recovery so make sure this is what you want. For me I only require my nightly backups on databases where I have this set up.

To shrink a log file as part of a maintenance plan task, first find out the fileID of the log file. To do this, open a new query window in SSMS and run select * from sys.sysfiles


From the table this displays it will show you the fileid of the database and log files. Make a note of the log file ID number that you want to shrink.

Now open a new maintenance plan (or add this as a step to an existing one) and drag in an  Execute T-SQL Statement Task box. Double click this to bring up the windows wher you can enter in your T-SQL code.

Type into this window the following, substituting DBNAME from the name of the database you want to shrink the log file for and fileID for the ID number we noted for the log file before.

use [DBNAME];
dbcc shrinkfile(fileID,500);


Be sure to include the square and rounded brackets and the semicolons as above. This will now attempt to shrink the log file down to 500mb or as close to that as it can. You can set this lower if you wish but if you are shrinking it too low and it needs to grow more you will end up with disk fragmentation.