Home > SQL Server Tips > Microsoft SQL Server > Automate scheduled backups for all databases
SQL Server Tips:
EMAIL THIS
 TIPS & NEWSLETTERS TOPICS 

MICROSOFT SQL SERVER

Automate scheduled backups for all databases


Mike Weaver
03.16.2003
Rating: --- (out of 5)


Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   


This script will 1) go through all SQL Server databases on a single server and create a device for each database and 2) schedule a single job with a task for each database to be backed up to a local directory of your choice. It is very useful if want to make complete scheduled backups of all your databases on a single server and you need to know that the devices and scheduled tasks have been created correctly and uniformly. It will drop all the old devices and scheduled tasks it created and recreate new devices and new scheduled tasks. With a few modifications, it could be turned into a stored procedure and thus you could pass parameters to to it. I use it on 20 servers containing over 30 databases for local and SAN backup scheduling. If a new database is added I just run the script again and I'm done. The task that is created will backup all of the databases and if one database fails it will move to the next database without stopping the task.

I developed this script to save DBA man-hours. For example, on a development box I was making backup devices and tasks daily and then a database would be dropped and I would have to go back and cancel the task and delete the device. I saved several hours a week with this script and it always works so I do not have to worry about this anymore. It was tested and run on SQL Server 2000.

-- create device for all database
SET NOCOUNT ON

-- get rid of all scheduled back ups
DECLARE RemoveDevice CURSOR FOR 
SELECT [name] FROM MASTER.DBO.sysdevices 
WHERE cntrltype = 2

DECLARE @DeviceName varchar(50)

OPEN RemoveDevice

FETCH NEXT FROM RemoveDevice
INTO @DeviceName
WHILE @@FETCH_STATUS = 0
BEGIN

--- REMOVE ALL DEVICES
 IF EXISTS (
     SELECT name 
     FROM MASTER.DBO.sysdevices 
     WHERE name = @DeviceName 
       AND cntrltype = 2
     )
     BEGIN
  EXEC master.dbo.sp_dropdevice @DeviceName
     END

FETCH NEXT FROM RemoveDevice INTO @DeviceName
END
CLOSE RemoveDevice
DEALLOCATE RemoveDevice

-- close after cleaning up bakups

-- Create new backup devices
DECLARE CreateDevice CURSOR FOR 
SELECT UPPER([name])AS Name
FROM MASTER.DBO.SYSDATABASES
WHERE [NAME] NOT IN('MODEL', 'tempdb', 'NORTHWIND', 'PUBS') 
EXCEPT

DECLARE @Prefix varchar(50),
 @Database varchar(50),
 @DumpLocation varchar(255),
 @runit varchar(100),
 @DBName varchar(50),
 @Directory varchar(50)

SELECT @Prefix = 'BACKUP_'
SELECT @Directory = 'c:BACKUP'

OPEN CreateDevice

FETCH NEXT FROM CreateDevice
INTO @DBName
WHILE @@FETCH_STATUS = 0
BEGIN

SELECT @DeviceName = @Prefix + @DBName --@Database
SELECT @DumpLocation = @Directory + @DeviceName + '.BAK'

-- DROP DEVICE LOGICAL  SELECT * FROM MASTER.DBO.sysdevices  WHERE cntrltype = 2

-- Create Backup Device with the prefix of BACKUP_
EXECUTE master.dbo.sp_addumpdevice 'disk', @DeviceName, @DumpLocation

FETCH NEXT FROM CreateDevice into @DBName
END

CLOSE CreateDevice
DEALLOCATE CreateDevice
GO

SET NOCOUNT OFF

-- ***************************************************************************
-- build jobs and task for each backup device
-- get all backup devices and create a backup job for them
USE MSDB
DECLARE Create_Job_and_Task CURSOR FOR 
SELECT name FROM MASTER.DBO.sysdevices WHERE cntrltype = 2 AND name
LIKE('BACKUP_%')

DECLARE @DatabaseName varchar(150),
 @DeviceName varchar(150),
 @fail_action int,
 @JobName varchar(150) ,
 @JOBID uniqueidentifier,
 @MAX  int,
 @NextStep int,
 @strCommand varchar(150),
 @strStepName varchar(150),
 @step_id int,
 @success_action int, 
 @Today char(8),
 @TimeToRun char(6)

 -- Start new backup schedule today
 SELECT @Today = CONVERT(varchar(8), GETDATE(), 112)
 -- Start time for backups
 SELECT @TimeToRun ='183000'      
 -- Go to next step on success 
 SELECT @success_action = 3  
 -- Go to next step on fail
 SELECT @fail_action = 3  
 -- To asign the next step number
   SELECT @NextStep = 1  
 -- How many task to create
 SELECT @MAX = (SELECT COUNT(*) FROM MASTER.DBO.sysdevices WHERE cntrltype = 2 AND name LIKE('BACKUP_%'))  
 -- Step counter
 SELECT @step_id = 1 
 -- The name of the Job Description
 SELECT @JobName = 'Backup All Databases'

 -- Procedure ID to execute 
 SELECT @JOBID = (SELECT job_id FROM sysjobs where Name = 'Backup All Databases') 

-- Create a JOB
IF EXISTS (SELECT job_id FROM sysjobs WHERE job_id = @JOBID) 
 --- Remove Old Jobs, Tasks, and Schedule
 BEGIN 
  -- Delete Steps
  DELETE sysjobsteps
  WHERE job_id = @JOBID
  -- Delete Job
  DELETE sysjobs 
  WHERE job_id = @JOBID   
  -- Delete Schedule
  DELETE sysjobschedules    
  WHERE job_id = @JOBID
 END

  -- Create new job
  EXECUTE  msdb.dbo.sp_add_job     
       @job_name = @JobName,
       @owner_login_name = N'sa', 
       @description = N'This job will backup all databases to their respective Devices.', 
       @category_name = N'Database Maintenance', 
       @enabled = 1, 
       @notify_level_email = 0, 
       @notify_level_page = 0, 
       @notify_level_netsend = 0, 
       @notify_level_eventlog = 2, 
       @delete_level= 0 

   SELECT @JOBID = (SELECT job_id FROm sysjobs where Name = @JobName)  

USE msdb
EXEC sp_add_jobschedule 
   @job_name = @JobName, 
   @name = 'Scheduled Backup',
   @freq_type = 4, -- daily
   @freq_interval = 1,
   @active_start_date = @Today,
   @active_start_time = @TimeToRun

USE msdb
EXEC sp_add_jobserver @job_name = @JobName, 
   @server_name = @@SERVERNAME

-- ***************************************************************************
-- start add task to the job
OPEN Create_Job_and_Task

FETCH NEXT FROM Create_Job_and_Task
INTO @DeviceName
WHILE @@FETCH_STATUS = 0

BEGIN
 SELECT @DatabaseName = SUBSTRING(@DeviceName,8,44)
 SELECT @strCommand = 'BACKUP DATABASE '+ @DatabaseName +  ' TO ' + @DeviceName + ' WITH INIT'
 SELECT @strStepName = @DeviceName

-- Add the job steps loop for each database
IF EXISTS (SELECT step_name FROM sysjobsteps WHERE step_name = @DeviceName AND job_id = @JOBID)
 BEGIN
 DELETE sysjobsteps
 WHERE step_name = @DeviceName AND job_id = @JOBID
 END

IF (@step_id <> @MAX)
 BEGIN
  SELECT @NextStep = @NextStep + 1
 END 
ELSE
 BEGIN
  SET @success_action = 1
  SET @fail_action = 2
 END
 
EXECUTE msdb.dbo.sp_add_jobstep   
      @job_id = @JOBID,
      @step_id = @step_id,
      @step_name = @DeviceName,
      @command = @strCommand,
      @database_name = @DatabaseName,  
      @server = N'', 
      @database_user_name = N'', 
      @subsystem = N'TSQL', 
      @cmdexec_success_code = 0, 
      @flags = 0, 
      @retry_attempts = 0, 
      @retry_interval = 1, 
      @output_file_name = N'',
      @on_success_step_id = @NextStep,
      @on_success_action = @success_action, 
      @on_fail_step_id = @NextStep,
      @on_fail_action = @fail_action 

SELECT @step_id = @step_id + 1

FETCH NEXT FROM Create_Job_and_Task
INTO @DeviceName
END

CLOSE Create_Job_and_Task
DEALLOCATE Create_Job_and_Task
GO

For More Information

  • Feedback: E-mail the editor with your thoughts about this tip.
  • More tips: Hundreds of free SQL Server tips and scripts.
  • Tip contest: Have a SQL Server tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize -- submit your tip today!
  • Ask the Experts: Our SQL, database design, Oracle, SQL Server, DB2, metadata, and data warehousing gurus are waiting to answer your toughest questions.
  • Forums: Ask your technical SQL Server questions--or help out your peers by answering them--in our active forums.
  • Best Web Links: SQL Server tips, tutorials, and scripts from around the Web.

Rate this Tip
To rate tips, you must be a member of SearchSQLServer.com.
Register now to start rating these tips. Log in if you are already a member.


Submit a Tip




Digg This!    StumbleUpon Toolbar StumbleUpon    Bookmark with Delicious Del.icio.us   


RELATED CONTENT
Microsoft SQL Server
Top 10 SQL Server development tips of 2008
Avoid cursors in SQL Server with these methods to loop over records
Implementing security audit in SQL Server 2008
What's new in SQL Server 2008 Reporting Services?
SQL Server replication methods: Snapshot, merge or transactional
New security features in SQL Server 2008 leave some work for you
How to disable the shrink database task in SQL Server 2000 and 2005
New datetime data types in SQL Server 2008 offer flexibility
SQL Server out of memory: Troubleshoot and avoid SQL memory problems
SQL Server errors, failures and other problems fixed from the trenches

SQL Server backup and recovery
Solve SQL Server errors and more from the DBA trenches -- part 2
Licensing a standby server for SQL Server replication
Can I encrypt and restore a database backup in SQL Server 2005?
SQL Server errors, failures and other problems fixed from the trenches
Get SQL Server log shipping functionality without Enterprise Edition
SQL Server 2008 backup compression pros and cons
SQL Server backups using SAN database snapshots
Tips for scheduling and testing SQL Server backups
Code to restore SQL Server databases in VB.NET
Tricking SQL Server into making full database backups
SQL Server backup and recovery Research

RELATED GLOSSARY TERMS
Terms from Whatis.com − the technology online dictionary
rollback  (SearchSQLServer.com)

RELATED RESOURCES
2020software.com, trial software downloads for accounting software, ERP software, CRM software and business software systems
Search Bitpipe.com for the latest white papers and business webcasts
Whatis.com, the online computer dictionary

DISCLAIMER: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.



SQL Server Development - .NET, C#, T-SQL, Visual Basic
HomeNewsTopicsITKnowledge ExchangeTipsAsk the ExpertsMultimediaWhite PapersIT Downloads
About Us  |  Contact Us  |  For Advertisers  |  For Business Partners  |  Site Index  |  RSS
SEARCH 
TechTarget provides enterprise IT professionals with the information they need to perform their jobs - from developing strategy, to making cost-effective IT purchase decisions and managing their organizations' IT projects - with its network of technology-specific Web sites, events and magazines.

TechTarget Corporate Web Site  |  Media Kits  |  Site Map




All Rights Reserved, Copyright 2005 - 2009, TechTarget | Read our Privacy Policy
  TechTarget - The IT Media ROI Experts