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

[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

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

Wonderful,

I need restore script too to restore all backup databases to new clean instance of SQL Server.  The explanation is as below:

Question:

How to backup SQL Server 2005 user databases in SQL script with all data (.sql) and restore this script of all databases on SQL server 2008

OR

How to restore all databases backed up through this script into new clean instance of SQL Server (backed up in SQL Server 2005 standard and restore to SQL Server 2008 web edition).

Can someone help me to backup all MS SQL Server 2005 standard user databases into SQL script (single file) and restore all databases with data from single backup script file to SQL server 2008 web edition.

Symptom:

Upgrade option for SQL Server standard 2005 to SQL SQL Server 2008 web edition is not supported. I've planned to upgrade SQL Server 2005 standard instance to SQL server 2008 web edition that is not supported and I'm thinking to backup all databases on SQL server 2005 standard into single script file (.sql) install new instance of SQL Server 2008 web edition and restore single script file into new instance. Please help me backup all databases into single script file.

OR

Alternative option is to generate script to restore all databases through your script in new installation of SQL Server 2008 web edition.

Help me please.

Saturday, September 04, 2010 7:04 PM by Atiq Ur Rahman Chaudhary

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

amazing things thanx

--------------------------------------------

my website is  

http://yogaball.us

Also welcome you!

Wednesday, November 17, 2010 3:58 PM by Zero Skateboards

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

"Word can clarify our thoughts, but there are lots of believed that can not be explained. I am certain in discussing some projects, we're one team, we have only one mind, and also 1 mind. So, it is difficult to us to operate collectively, besides we are “clicked”. Comprehensively, with comparing and studying quite a few projects, I realize that not most folks implement unique and clear layout. But you are the most effective one particular, you gave me the most critical thing to turn out to be accomplishment and that i discovered “jewelry”. “Jewelry” I meant is you. You might be potential designer, potential website programmer, you might be inventive men and women, and i look at you to turn into my team to build or build some long term job in my corporations. When you don’t mind, you are able to chat with me, so I can predict your possible and big skills. I'm welcome to accomplish that. Given that you happen to be the most famous individual that I knew, it really is great to let you know for recruitment program will be held as quickly as doable."

--------------------------------------------

my website is  

http://chineseastrology.us

Also welcome you!

Tuesday, December 07, 2010 12:21 AM by Climbing Gear

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

Nurture passes nature.

-----------------------------------

Monday, December 20, 2010 1:59 AM by cheap ipad accessories

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

<a href=www.jewelforless.com/pandora-jewelry>silver pandora bracelet</a>

i0p0418j

Sunday, April 17, 2011 9:36 PM by tateassupyita

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

xilisoft dvd audio ripper

dvd to dv avi

<a href=www.dvdripper.org/.../>convert dvd to ipod nano</a>

 dvd to mkv

pq dvd to ipod

dvd to wii

stream dvd to ps3

transfer dvd to ipod touch

 i0p0420301d

Wednesday, April 20, 2011 2:56 AM by flieniapaigue

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

I don't see why spend time in creating scripts to backup databases while there are so many easier ways to do it.

First and most obvious option would be using Management Studio. There are also many utilities available like this http://sqlbackupandftp.com which lets you backup more than one database at a time. This tool even lets you copy your backup to a remote server.

Friday, July 22, 2011 5:05 PM by AlexGreen

Leave a Comment

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