[SQL] Scripting backup and restore all databases on a server (Part 1 - Simple Case)

We just migrated a group of production sites from one hosting environment to another. The new environment has staging and production servers, so we really completed two migrations. There were a lot of databases, and if you've been following my blog at all you probably know that I love to script repetetive tasks - not (only) from laziness, but from a desire to avoid typographical errors due in repetetive manual work.

First, I backed up all databases on the old server. I ran this script, which generated a DOS batch file:

DECLARE @BACKUP_DIRECTORY varchar(100)
SET @BACKUP_DIRECTORY = 'E:\DB_Backups\'

SELECT
'osql -E -d master -Q "BACKUP DATABASE '
+ QUOTENAME(CATALOG_NAME)
+ ' TO DISK = N'''+@BACKUP_DIRECTORY+''
+ CATALOG_NAME
+ '.bak'' WITH INIT, NOUNLOAD, NAME = N'''
+ CATALOG_NAME
+ 'backup'', NOSKIP , STATS = 10, NOFORMAT"'
FROM INFORMATION_SCHEMA.SCHEMATA
WHERE CATALOG_NAME NOT IN ('master','tempdb','msdb','model','Northwind','pubs')

So I shifted the Query Analyzer output to text mode (ctrl-t), ran the above query, and saved the results to a file - BackupDatabases.bat. I wanted a batch file so I could test the migration up to the cutover day, at which time I'd need to do a final backup of the old sites. Looking good so far.1

At this point, I zipped up the backup directory (full of .bak files) and copied it to the new server. Now it's time to restore all those .bak files. The following batch file rips through a directory, restoring everay .bak file it finds:

@ECHO OFF
SET DBDIRECTORY=D:\Program Files\Microsoft SQL Server\MSSQL\Data
SET BACKUPDIRECTORY=C:\DB_Backups

PUSHD %BACKUPDIRECTORY%
FOR %%in (*.bakdo CALL :Subroutine %%A
POPD

TITLE 
Finished restoring database backups
ECHO Finished restoring database backups
PAUSE

GOTO
:EOF

:Subroutine
set DBNAME=%~n1

TITLE Restoring %DBNAME% Database
ECHO Restoring %DBNAME% Database

::PUT DATABASE IN SINGLE USER MODE TO ALLOW RESTORE
osql --d master -"alter database %DBNAME% set single_user with rollback immediate"

::RESTORE DATABASE
osql --d master -"restore database %DBNAME% from disk='%~dp0\%DBNAME%.bak' WITH MOVE 

'%DBNAME%_Data' 
TO '%DBDIRECTORY%\%DBNAME%_Data.MDF'MOVE '%DBNAME%_Log' TO 

'%DBDIRECTORY%\%DBNAME%_Log.LDF'"

::GRANT PERMISSION TO ASPNET USER - UNCOMMENT IF DESIRED
::osql -E -d %DBNAME% -Q "sp_grantdbaccess '%COMPUTERNAME%\ASPNET'"
::osql -E -d %DBNAME% -Q "sp_addrolemember 'db_owner', '%COMPUTERNAME%\ASPNET'"

::RESTORE TO MULTI USER
osql --d master -"alter database %DBNAME% set multi_user"

GOTO:EOF

Unfortuantely, it didn't work for a few of the databases. What had I done wrong? Well, I'd assumed the simple case (hence the title of this post) - I'd assumed that the database logical names matched the database name, so Example.bak would restore to Example_Data (in Example_Data.mdf) and Example_Log (in Example_Log.ldf). That's not always the case, especially if a database has been copied via backup / restore / rename.

I'll talk about how to script backup / restore when database logical names don't match the database name next...

1 You can use of course set up SQL Server jobs to backup your databases, but there are advantages to having a single batch file which backs up all databases in one go.

Published Thursday, July 27, 2006 11:37 PM by Jon Galloway
Filed under: ,

Comments

# [SQL] Scripting backup and restore all databases on a server (Part 2 - Extra CreditM)

In the first post of this series, I discussed scripting database restore statements. It seems simple

Friday, July 28, 2006 3:55 AM by JonGalloway.ToString()

# re: [SQL] Scripting backup and restore all databases on a server (Part 1 - Simple Case)

I favor a simpler approach: writing dynamic SQL inside a stored proc and then calling that stored proc in a job, OSQL, whatever; i.e., it's reusable and doesn't care what the "context" is. Here's what I use:

/*

 This script makes a backup and appends a Date + Time string at the end. It

accepts several (hopefully obvious) parameters allowing you

to choose between backing up a single database or all databases

on the SQL Server. You can also have it make a new folder and write

all backups to that folder.

 Scott Whigham - http://www.LearnSqlServer.com

*/

USE Master

IF ( SELECT OBJECTPROPERTY ( OBJECT_ID('sp_BackupAllDatabases'), 'IsProcedure') ) = 1

  DROP PROC sp_BackupAllDatabases

GO

CREATE  PROC sp_BackupAllDatabases  

(

  @BackupFolderLocation NVARCHAR(128) = 'D:\'

, @BackupExtension CHAR(3) = 'BAK'

, @BackupThisDatabaseOnly SYSNAME = NULL

, @IncludeSecondsInTimeStamp BIT = 1

, @MakeNewFolder BIT = 1

, @FolderBaseName SYSNAME = 'SQLServerDatabaseBackups'

)

AS  

SET NOCOUNT ON  

DECLARE @Counter TINYINT, @DateTime DATETIME, @DBName SYSNAME,  @CmdShellString SYSNAME

, @DateString VARCHAR(8), @TimeString VARCHAR(12), @BackupFileName VARCHAR(512)

SELECT @DateTime = GETDATE(), @DateString = CONVERT(VARCHAR(8), @DateTime, 112)  

, @TimeString = CONVERT(VARCHAR(12), @DateTime, 14)  

IF ( @IncludeSecondsInTimeStamp = 0)

  SET @TimeString = LEFT(REPLACE(@TimeString,':',''), 4)  -- REPLACE pulls out the ":" out of the TimeString; LEFT gets the first four characters

ELSE

 SET @TimeString = LEFT(REPLACE(@TimeString,':',''), 6)  

IF ( @MakeNewFolder=1) BEGIN

  IF ( @FolderBaseName IS NOT NULL)

     BEGIN

        DECLARE @ReturnCode INT

        SET @CmdShellString = 'md ' + @BackupFolderLocation + @FolderBaseName + '_' +  @DateString + '_' + @TimeString

        EXEC @ReturnCode = xp_cmdshell @CmdShellString

        IF ( @ReturnCode = 0 )

           SET @BackupFolderLocation = @BackupFolderLocation + @FolderBaseName + '_' +  @DateString + '_' + @TimeString + '\'

        ELSE

           BEGIN

              RAISERROR ('Unable to create this folder. Backup is terminating', 16, 1)

              RETURN -100

           END

     END

  ELSE

     BEGIN

        RAISERROR ('You said that you wanted to create a folder but did not pass in the folder name (@FolderBaseName) - try again', 16, 1)

        RETURN -100

     END

END

IF (@BackupThisDatabaseOnly IS NOT NULL) BEGIN -- User wants only to back up a single database:

  SELECT @BackupFileName = @BackupThisDatabaseOnly + '_' +  @DateString + '_' + @TimeString + '.' + @BackupExtension  

  EXEC ('BACKUP DATABASE [' + @BackupThisDatabaseOnly + '] TO DISK ='''  

     + @BackupFolderLocation + @BackupFileName + '''')  

  RETURN

END

DECLARE @HoldingTable TABLE ( ID INT IDENTITY ( 1, 1 ), DatabaseName SYSNAME )  

INSERT INTO @HoldingTable  

  SELECT name FROM master.dbo.sysdatabases  

  WHERE name NOT IN ( 'tempdb', 'model', 'northwind', 'pubs', 'AdventureWorks' )  

SELECT @Counter = MIN ( ID ) FROM @HoldingTable  

WHILE @Counter IS NOT NULL BEGIN  

  SELECT @DBName = DatabaseName FROM @HoldingTable WHERE ID = @Counter  

  SELECT @BackupFileName = @DBName + '_' +  @DateString + '_' + @TimeString + '.' + @BackupExtension

  EXEC ('BACKUP DATABASE [' + @DBName + '] TO DISK ='''  

     + @BackupFolderLocation + @BackupFileName + '''')  

  DELETE FROM @HoldingTable WHERE ID = @Counter  

  SELECT @Counter = MIN ( ID ) FROM @HoldingTable  

END  

GO

EXEC sp_BackupAllDatabases

Friday, July 28, 2006 12:19 PM by Scott Whigham (LearnSqlServer.com)

# re: [SQL] Scripting backup and restore all databases on a server (Part 1 - Simple Case)

Incase anyone lands on here looking for a free backup solution, I'd recommend you check out Jasper Smith's ExpressMaint utility:

http://www.sqldbatips.com/showarticle.asp?ID=29

Friday, July 28, 2006 3:59 PM by Karl

# Interesting Finds: July 28, 2006

Friday, July 28, 2006 11:25 PM by Jason Haley

# Technical Related Notes » Blog Archive » links for 2006-07-29

# re: [SQL] Scripting backup and restore all databases on a server (Part 1 - Simple Case)

interesting

Tuesday, June 05, 2007 12:00 AM by Panayotis

# free file restore

When you are looking for free restore deleted file websites and web pages, be sure to utilize all of the sources at your disposal.

Sunday, October 07, 2007 10:57 AM by free file restore

Leave a Comment

(required) 
(required) 
(optional)
(required)