天极Yesky
  • 笔记本电脑
    笔记本
  • 台式电脑
    台式机
  • 手机
    手机
  • 电脑硬件DIY
    DIY硬件
  • CPU
    主板
    音箱
  • 硬盘
    显卡
    键鼠
  • 内存光驱
    显示器
    机箱电源

  • 数码相机DC
    数码相机
  • MP3播放器
    MP3/MP4
  • 数码摄像机DV
    摄像机
  • 电脑外设
    外设
  • 网络
    网络
  • 服务器
    服务器
  • 数字家庭
    数字家庭
  • 群乐
    群乐
  • 产品报价 行情 商家 新闻 评测 | 软件 设计 网页 开发 安全 论坛 E时代 游戏 图片 壁纸 下载 网摘 博客 索尼专区 Vista 科技奥运
    天极网
    Automate scheduled backups for all databases
    作者: David Pye
    出处:
    责任编辑:
    [ 2004-06-17 18:46 ]


    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.
    笔名:
    请您注意:

     遵守国家有关法律、法规,尊重网上道德,承担一切因您的行为而直接或间接引起的法律责任。

     天极网拥有管理笔名和留言的一切权利。
    相关内容