MSSQL: Back up all databases.

Posted November 6th, 2012


Backs up all databases contained in a Microsoft SQL Server instance.

--
-- Backup all databases except the system databases.
-- Backup files will be saved in the format DBname_YYYDDMM_HHMMSS.bak.
--

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')  -- exclude these databases

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @name

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

       FETCH NEXT FROM db_cursor INTO @name
END

CLOSE db_cursor   
DEALLOCATE db_cursor