Search code examples
sqlsql-servert-sqlsql-server-2008backup

SQL Server: backup all databases


I was wondering if there was any way of making a backup of an entire SQL Server (we are using SQL Server 2008) at regular intervals to a specific location. I know we are able to backup single specific databases but for ease of use and not having to set up a backup each time I want a new database, is there a way to do this?

If there is however, I must have a way of restoring just a single database from that server backup easily as though I have backed them up individually.

The method used will just be a pure backup and not a difference so no need to worry about complications.


Solution

  • You can run the following script, just change the @path variable to where you want to store the databases.

    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 = 'C:\Backup\'  
    
    SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112) 
    
    DECLARE db_cursor CURSOR FOR  
    SELECT name 
    FROM master.dbo.sysdatabases 
    WHERE name NOT IN ('master','model','msdb','tempdb')  
    
    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
    

    Obtained from:

    http://www.mssqltips.com/sqlservertip/1070/simple-script-to-backup-all-sql-server-databases/