Tip

Automate scheduled backups for all databases

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

    Requires Free Membership to View

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.


This was first published in February 2005

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

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.