Force Shrink a SQL transaction log file

Imagine this. Your database transaction log has grown tremendously. You don't have enough space to do a backup of it and proper truncation. You do, however, have a backup of your database and are sure that you can restore it without any issue. What can you do?

Here is a script that I use to force shrink transaction logs. Note that this can potentially be harmful, so make sure that you have a working backup of your database. Having said that, I've done this on a number of log files, some growing up to 200GB big, and I've not had any problems whatsoever.

Replace the database_name variable in the first line with the actual name of your database (enclose in single quotes)

    DECLARE @DBName nvarchar(100) = 'database_name';

    -- Declare the variable to be used
    DECLARE @sql nvarchar(1000), @exec nvarchar(300), @logfile nvarchar(100);

    -- Initialize Exec StoredProc
    SET @exec = QUOTENAME(@DBName) + '.sys.sp_executesql'

    -- Get Logfile name
    SET @sql = 'Select @
    logfile=Name from sys.database_files where type=1;'
    EXEC @exec @sql, @Params = N'@
    logfile nvarchar(100) OUTPUT', @logfile=@logfile OUTPUT

    -- Shrink Logfile
    SET @sql = 'ALTER DATABASE '+ @DBName +' SET RECOVERY SIMPLE WITH NO_WAIT;'
    SET @sql += ' DBCC SHRINKFILE (['+ @
    logfile +'], 1);'
    SET @sql += ' ALTER DATABASE '+ @DBName +' SET RECOVERY FULL WITH NO_WAIT;'
    EXEC @exec @sql;


    The process takes a bit of time. Around 20mins for every 100GB.

    Good luck!

    Comments

    Popular posts from this blog

    Windows RRAS VPN configuration when server is behind NAT

    Lenovo X1 Carbon Battery Problem - Plugged, Not Charging

    Multiple Remote Desktop sessions on Windows XP