Categories
Sql Server

How To Backup All Database In SQL Server Which Are Online

How To Backup All Database In SQL Server Which Are Online

In this tutorial i will explain How To Backup All Database In SQL Server Which Are Online.We are using CURSOR to achieve this.Cursor is a database object used by applications to manipulate data in a set on a row-by-row basis.

Script:

DECLARE @name VARCHAR(50) -- database name  
DECLARE @path VARCHAR(256) -- path for backup files  
DECLARE @fileName VARCHAR(256) -- filename for backup  
DECLARE @fileDate VARCHAR(20) -- used for file name 

SET @path = 'G:\SQLDATA\Backup\'  

SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),110) 

DECLARE db_backup_cursor CURSOR FOR  
SELECT name 
FROM sys.databases 
WHERE name NOT IN ('master','model','msdb','tempdb') and state_desc='ONLINE' 

OPEN db_backup_cursor  
FETCH NEXT FROM db_backup_cursor INTO @name   

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

       FETCH NEXT FROM db_backup_cursor INTO @name   
END   

CLOSE db_backup_cursor  
DEALLOCATE db_backup_cursor