Loading

Tuesday, February 15, 2011

Truncate (or Purge) Transaction Log in SQL 2008

Over the weekend one of our critical servers ran out of disk space on the volume which contains the transaction logs & all hell broke loose.  Our DBA was at a wedding and couldn't be reached so it was up to me to get things working ASAP.  I've truncated logs before in SQL 2005 and SQL 2000 (I've even written about it on this blog) with the following:
BACKUP LOG <DataBase_Name>
WITH TRUNCATE_ONLY
GO
DBCC SHRINKFILE (2,1, TRUNCATEONLY)
GO
However, our dear friends at Microsoft have removed TRUNCATEONLY from SQL 2008. Searching the 'net I found a few fragmented suggestions. But the one that was the bomb and corrected things for me right away was this great post by Otto R. Radke.  There is only one item that has to be customized (highlighted) with the DB name and voila, it fixed by problem by truncating my huge transaction log.  Thanks Otto!

------------------------------------------------------------------------------
-- Otto R. Radke - http://ottoradke.com
-- Info: T-SQL script to shrink a database's transaction log. Just set the
-- database name below and run the script and it will shrink the
-- transaction log.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
-- Update the line below with the name of the database who's transaction
-- log you want to shrink.
------------------------------------------------------------------------------
USE <YourDatabaseName>
------------------------------------------------------------------------------
-- Don't change anything below this line.
------------------------------------------------------------------------------
GO
-- Declare variables
DECLARE @SqlStatement as nvarchar(max)
DECLARE @LogFileLogicalName as sysname
-- Alter the database to simple recovery
SET @SqlStatement = 'ALTER DATABASE ' + DB_NAME() + ' SET RECOVERY SIMPLE'
EXEC ( @SqlStatement )
-- Make sure it has been altered
SELECT [name], [recovery_model_desc] FROM sys.databases WHERE [name] = DB_NAME()
-- Set the log file name variable
SELECT @LogFileLogicalName = [Name] FROM sys.database_files WHERE type = 1
-- Shrink the logfile
DBCC Shrinkfile(@LogFileLogicalName, 1)
-- Alter the database back to FULL
SET @SqlStatement = 'ALTER DATABASE ' + DB_NAME() + ' SET RECOVERY FULL'
EXEC ( @SqlStatement )
-- Make sure it has been changed back to full
SET @SqlStatement = 'SELECT [name], [recovery_model_desc] FROM ' + DB_NAME() + '.sys.databases WHERE [name] = ''' + DB_NAME() + ''''
EXEC ( @SqlStatement )
------------------------------------------------------------------------------

1 comment: