MSSQL: Back up all transaction logs.

Posted November 6th, 2012


Backs up all database transaction logs within a Microsoft SQL Server instance except for databases set to simple recovery mode.

--
-- Backup transaction logs for all databases except the system databases.
-- Backup files will be saved in the format DBname_YYYDDMM_HHMMSS.trn.
--

DECLARE @name VARCHAR(50) -- Database name.
DECLARE @path VARCHAR(256) -- Path to backup folder.
DECLARE @fileName VARCHAR(256) -- Filename for backup.
DECLARE @fileDate VARCHAR(20) -- Used for file name.

-- Specify database backup directory.
SET @path = 'C:\Backup\'

-- Specify filename format.
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112) + REPLACE(CONVERT(VARCHAR(20),GETDATE(),108),':','')


DECLARE db_cursor CURSOR FOR
SELECT name
FROM master.dbo.sysdatabases
WHERE name NOT IN ('master','model','msdb','tempdb') AND DATABASEPROPERTYEX(name, 'Recovery') IN ('FULL','BULK_LOGGED')

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name

WHILE @@FETCH_STATUS = 0
BEGIN
       SET @fileName = @path + @name + '_' + @fileDate + '.trn'
       BACKUP LOG @name TO DISK = @fileName

       FETCH NEXT FROM db_cursor INTO @name
END

CLOSE db_cursor
DEALLOCATE db_cursor