Important alert: (current site time 7/15/2013 7:22:37 PM EDT)
 

VB icon

Backup All Databases

Email
Submitted on: 3/23/2001 9:12:15 AM
By: PHendryx  
Level: Advanced
User Rating: By 13 Users
Compatibility: SQL Server 7.0, SQL Server 6.5 and earlier
Views: 38990
(About the author)
 
     This script was written because I have a server with about 115 client databases on it. It was a rather hard task to try to backup all of them by hand and I didnt want to spend a few grand on a good piece of backup software. Basicly, this script just loops thru all the databases on a given server and backs them up somewhere on that machine. From there, you can compress them and transfer them off site, etc. The backup will include MSDB and Master databases for complete disaster recovery. This script is meant to run daily. On sundays, it will perform full backups of each database and on the other days it does a differential backup. This script will NOT overwrite any files, it stores the backups in the following format: dbname_(full or diff)_20010323.bak Any questions, please email me.
 
code:
Can't Copy and Paste this?
Click here for a copy-and-paste friendly version of this code!
 
Terms of Agreement:   
By using this code, you agree to the following terms...   
  1. You may use this code in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this code (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this code from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the code or code's description.
				
--**************************************
-- Name: Backup All Databases
-- Description:This script was written because I have a server with about 115 client databases on it. It was a rather hard task to try to backup all of them by hand and I didnt want to spend a few grand on a good piece of backup software. Basicly, this script just loops thru all the databases on a given server and backs them up somewhere on that machine. From there, you can compress them and transfer them off site, etc. The backup will include MSDB and Master databases for complete disaster recovery.
This script is meant to run daily. On sundays, it will perform full backups of each database and on the other days it does a differential backup.
This script will NOT overwrite any files, it stores the backups in the following format:
dbname_(full or diff)_20010323.bak
Any questions, please email me.
-- By: PHendryx
--
-- Returns:If you run this on a schedule, you dont see anything, but if you run it in the query analyzer, you will see different stats about each database as its backing up.
--
-- Side Effects:None. Very low CPU usage.
--
--This code is copyrighted and has-- limited warranties.Please see http://www.Planet-Source-Code.com/vb/scripts/ShowCode.asp?txtCodeId=284&lngWId=5--for details.--**************************************

--*****************************************************************************
--Developed By: Paul Hendryx (paulh@tekker.com)
--Date: 3/20/01 3:21 PM
--Current Version: 1.0
--
--The only line that should be edited is the @BackupDirectory line. The
--rest should only be modified by experienced professionals.
--*****************************************************************************
--Declare our variables
DECLARE @BackupFile varchar(255), @DB varchar(30), @Description varchar(255), @IsSunday bit
declare @Name varchar(30), @MediaName varchar(30), @HasFullBackup bit, @BackupDirectory nvarchar(200)
--Set the backup directory.. dont forget the trailing \ otherwise it wont work.
set @BackupDirectory = 'c:\backup\'
--Loop thru all the databases that we should backup. Northwind is just an example db and tempdb and model arent needed.
declare Database_Cursor cursor for select name from sysdatabases where name <> 'tempdb' and name <> 'model' and name <> 'Northwind'
open Database_Cursor
fetch next from Database_Cursor into @DB
while @@fetch_status = 0
begin
	--See if its sunday.. 1=is sunday, 0=is not sunday
	set @IsSunday = 
		case Datepart(dw, CURRENT_TIMESTAMP)
			when 1 then 1 else 0
		end
	--Set some stuff so it looks pretty in sql server
	set @Name = @DB + '( Daily BACKUP )'
	set @MediaName = @DB + '_Dump' + CONVERT(varchar, CURRENT_TIMESTAMP , 112)
	set @BackupFile = @BackupDirectory + + @DB + '_' + 
		CASE @IsSunday 
			WHEN 3 THEN 'Full' ELSE 'Diff' 
		END + '_' + 
		CONVERT(varchar, CURRENT_TIMESTAMP , 112) + '.bak'
	set @Description = 
		CASE @IsSunday 
			WHEN 1 THEN 'Normal' ELSE 'Differential' 
		END + ' BACKUP at ' + CONVERT(varchar, CURRENT_TIMESTAMP) + '.' 
	--Check to see if this db has a full backup. If its the master, we have to do a full backup.
	set @HasFullBackup = 0
	if (select count(*) from msdb.dbo.backupset where database_name = @DB) > 0 or @DB = 'master'
	begin
		--This database has a full backup.
		set @HasFullBackup = 1
		--If its sunday, then we do a full backup anyways.
		set @BackupFile = @BackupDirectory + @DB + '_' + 
			CASE @IsSunday 
				WHEN 3 THEN 'Full' ELSE 'Diff' 
			END + '_' + 
			CONVERT(varchar, CURRENT_TIMESTAMP , 112) + '.bak'
		--Set some more pretty stuff for sql server.
		set @Description = 
			CASE @IsSunday 
				WHEN 1 THEN 'Full' ELSE 'Differential' 
			END + ' BACKUP at ' + CONVERT(varchar, CURRENT_TIMESTAMP) + '.' 
	end	
	else
	begin
		--This db does not have a full backup.
		set @HasFullBackup = 0
		--Full backup time.
		set @BackupFile = @BackupDirectory + @DB + '_' + 'Full' + '_' + 
			CONVERT(varchar, CURRENT_TIMESTAMP , 112) + '.bak'
		--Set some more pretty stuff for sql server.
		set @Description = 'Full' + ' BACKUP at ' + CONVERT(varchar, CURRENT_TIMESTAMP) + '.' 
	end
	--If it is sunday, or the current db is master, or if this db has not had a full backup, the do a full backup.
	if @IsSunday = 1 or @DB = 'master' or @HasFullBackup = 0
	begin
		BACKUP DATABASE @DB TO DISK = @BackupFile 
		WITH NAME = @Name, DESCRIPTION = @Description , 
		MEDIANAME = @MediaName, MEDIADESCRIPTION = @Description , 
		STATS = 10
	end
	--This would be a daily differentail backup.
	if @IsSunday = 0 and @DB <> 'master' and @HasFullBackup <> 0
	begin
		BACKUP DATABASE @DB TO DISK = @BackupFile 
		WITH DIFFERENTIAL, NAME = @Name, DESCRIPTION = @Description , 
		MEDIANAME = @MediaName, MEDIADESCRIPTION = @Description , 
		STATS = 10
	end
	--Print some pretty info so we can debug.
	print '------------------------------------------------------------------------'
	print ''
	print 'DB: ' + @DB
	print 'Name: ' + @Name
	print 'Media Name: ' + @MediaName
	print 'Backup File: ' + @BackupFile
	print 'Description: ' + @Description
	print 'Is Sunday (0 or 1): ' + str(@IsSunday)
	print 'DB has full backup (0 or 1): ' + str(@HasFullBackup)
	print ''
	print '------------------------------------------------------------------------'
	print '------------------------------------------------------------------------'
	print''
	fetch next from Database_Cursor into @DB
end
close Database_Cursor
deallocate Database_Cursor


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this code (in the Advanced category)?
(The code with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments
3/25/2001 5:40:58 PMKirminator

Nice work!
(If this comment was disrespectful, please report it.)

 
3/28/2001 11:57:45 AMDBA

Very nice script; the effort that went into refining it shows.

Main comment I have is I would suggest you back up both model and Northwind. Model is important because it governs the inital settings of each DB and may have extensive schema.

Northwind may be used by developers and you'll have someone come to you someday asking you to restore the DB after they blow it up.
(If this comment was disrespectful, please report it.)

 
3/28/2001 7:43:46 PMSoftwareMaker

Hi Paul,

Thanks for your reply. I finally got it NOW. I have always been working on DB4 and Access and am just migrating or say Upgrading to SQL Server. Therefore the ignorance of the T-SQL Syntax.

Pardon me for this ignorance. I have a lot to learn from you.
(If this comment was disrespectful, please report it.)

 
3/29/2001 1:09:22 AMQQQ

Good code. Vote u 4 stars
(If this comment was disrespectful, please report it.)

 
3/29/2001 10:07:18 AMPaul Hendryx

Thanks QQQ, I appriciate it.
(If this comment was disrespectful, please report it.)

 
3/29/2001 10:08:48 AMPaul Hendryx

SoftwareMaker: No problem. Glad I could help. I dont claim to be the best programmer/scripter or a wizard or anything, but I know Im good at what I do.
(If this comment was disrespectful, please report it.)

 
7/5/2001 3:53:57 PMCharles Kincaid

Only one improvement: As you are running this script once per day, you should move the "Is It Sunday" test to before the main loop.

I presume that your backups won't take all day but if this script were started late on a Sturday it might cross into Sunday resulting in some databases beng processed one way and some the other.
(If this comment was disrespectful, please report it.)

 
2/21/2002 9:26:00 AMBen

Fast and simple, does the job
(If this comment was disrespectful, please report it.)

 
9/13/2002 8:42:16 AM

Considering it took me 2.2 seconds to find all the code in your script using SQL Server books online with the addition of being able to overwrite existing files I give it a 3. Not a bad job though...
(If this comment was disrespectful, please report it.)

 
2/4/2003 12:42:45 AM

I want to have a
(If this comment was disrespectful, please report it.)

 
2/4/2003 12:43:33 AM

I want to have a "backup" facility in my database that is being developed in Access. What should I do?

Thanks in advance for your cooperation.
(If this comment was disrespectful, please report it.)

 
6/18/2003 1:36:19 PM

The code is concise and the comments are descriptive. I copied and pasted the code and received an error the the device can't be accessed -- it seems to be that I can't jus tspecify TO = 'filename.bak', the file needs to first be registered as a backup device which I can't do if I change the name every day to reflect the new date. Any helpful suggestions?
(If this comment was disrespectful, please report it.)

 
8/11/2003 1:08:44 PM

I give it 5 (*)'s, so do you have a stored proceedure that will ready that same directory and do a restore or all those same databases?
(If this comment was disrespectful, please report it.)

 
8/28/2003 7:06:52 AM

I request you to Kindly send me a Stored procedure for SQL server 2000 databases.
I was not able to test this on Sql server 2000, it says
(If this comment was disrespectful, please report it.)

 
8/28/2003 7:07:41 AM

I request you to Kindly send me a Stored procedure for SQL server 2000 databases.
I was not able to test this on Sql server 2000, it says "Invalid object name sysdatabases".I changed that to "sysobjects" and applied.
now the error:
"Could not locate entry in sysdatabases for database 'sysobjects'. No entry found with that name. Make sure that the name is entered correctly."
mailto : afewgwman@yahoo.co.in
(If this comment was disrespectful, please report it.)

 
10/30/2003 12:33:28 PM

HI, i tried this on my MSSQL server 7.0 and when i try to run it on the query analyzer or profiler it gives me this error, what could it be? thanks

[Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near the keyword 'is'.


(If this comment was disrespectful, please report it.)

 
10/23/2004 4:55:52 PM

I tried to run it on my local server but get the error message:
Server: Msg 208, Level 16, State 1, Line 7
Invalid object name 'sysdatabases'.

Could anyone tell me what this
(If this comment was disrespectful, please report it.)

 
11/27/2004 2:56:57 PM

Worked like a champ. 5 for me.

Thanks.
(If this comment was disrespectful, please report it.)

 
1/9/2005 9:35:57 PM

How do you automate the running of this script?
(If this comment was disrespectful, please report it.)

 
5/10/2005 5:58:21 AMRobin Cleland

Maybe also add USE [master] at the beginning of the script, as I think this might help when users start the script from their default databse in query analyser
(If this comment was disrespectful, please report it.)

 
12/6/2006 7:43:19 AMchanaka

This is excellent.coz i tried 40 hours tofind this type of code.Finally i got it, & thank you very much. i hope more good example about JOBS in SQL also

(If this comment was disrespectful, please report it.)

 
3/22/2007 4:22:22 AMCN

to use in MSDE add (at begin)
use master
(If this comment was disrespectful, please report it.)

 
2/2/2011 10:54:13 AMAUSTIN

Great Code!

(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular code, please click here instead.)
 

To post feedback, first please login.