步骤之间的SQL Server代理作业传递参数?

时间:2013-04-12 06:51:13

标签: sql database-backups sql-server-agent

我正在创建一些作业来备份我的数据库,然后压缩它们。我想在一步中备份数据库并在下一步中压缩文件,所以我想将文件的名称从第一步传递到第二步。有谁知道我应该如何在步骤之间传递变量?

我知道我可以将这一切都放在一个步骤中,或者我没有时间在文件名中来完成这项工作,但我想在备份文件名中保留日期和时间,我希望保持步骤分离,以便更容易查看备份失败时失败的原因。

如果将值保存到临时表中是唯一的方法,我可以这样做,但我认为应该有更好的方法。

我在MS SQL 2005和2008上运行它

-- ################################################################################
-- ################################################################################
-- ##                                                                            ##
-- ##                 Create a Backup job for each database.                     ##
-- ##                                                                            ##
-- ################################################################################
-- ################################################################################

SET NOCOUNT ON

-- Path that all Backups will get saved to.
DECLARE @BackupPathName nvarchar(max)
--SET @BackupPathName = N'\\SERVER\FILES\Backups\' 
SET @BackupPathName = N'D:\FILES\Backups\' 

DECLARE @ServerName nvarchar(30)
--SET @ServerName = 'SERVER'
SET @ServerName = N'SERVER'

DECLARE @7z_path nvarchar(max)
SET @7z_path = N'D:\FILES'

DECLARE @7zAlgorithm nvarchar(max)
  SET @7zAlgorithm = N'-t7z'   -- better compression
--SET @7zAlgorithm = N'tbzip2' -- faster compression

DECLARE @CompressionLevel nvarchar(max)
--SET @CompressionLevel = N'-mx0' -- Dont compress
--SET @CompressionLevel = N'-mx1' -- Low
--SET @CompressionLevel = N'-mx3' -- Fast
  SET @CompressionLevel = N'-mx5' -- Normal
--SET @CompressionLevel = N'-mx7' -- Maximum
--SET @CompressionLevel = N'-mx9' -- Ultra

-- Get a list of the databases, except for the ones listed in the where section of the query
DECLARE @AllDatabases TABLE(
    ROW_NUM  int,
    DbName   sysname)

INSERT INTO @AllDatabases (ROW_NUM, DbName)
SELECT ROW_NUMBER() OVER(ORDER BY [name]) AS ROW_NUM, [name] AS DbName
FROM sys.databases
WHERE [name] NOT IN (N'master', N'model', N'msdb', N'tempdb') 

-- While loop to go through each database
DECLARE @MaxRowNum int
SET @MaxRownum = (SELECT MAX(ROW_NUM) FROM @AllDatabases)

DECLARE @Iter int
SET @Iter = (SELECT MIN(ROW_NUM) FROM @AllDatabases)

WHILE @Iter <= @MaxRownum
BEGIN

    -- Name of the Database
    DECLARE @DbName sysname
    SET @DbName = NULL
    SET @DbName = (SELECT TOP(1) DbName FROM @AllDatabases WHERE ROW_NUM = @Iter)

    -- Name of the job to be created
    DECLARE @JobName nvarchar(128)
    SET @JobName = NULL
    SET @JobName = 'Backup ' + @DbName + ' Database job'

    -- Script to create the Job
    DECLARE @CreateJob nvarchar(max)
    SET @CreateJob = NULL
    SET @CreateJob = 
    'USE msdb; 
     DECLARE @Job_Number uniqueidentifier
     EXEC sp_add_job @job_name = N''' + @JobName + ''', @job_id = @Job_Number OUTPUT;
     SELECT @Job_Number
    '

    -- Table to return the Job ID to
    DECLARE @Job_ID_Table TABLE(
        Job_ID  uniqueidentifier)

    -- Variable to hold the Job ID
    DECLARE @Job_ID uniqueidentifier
    SET @Job_ID = NULL

    -- Create the Job
    INSERT INTO @Job_ID_Table
    EXEC sp_executesql @statement = @CreateJob

    -- Get the ID Number for the Job
    SET @Job_ID = (SELECT TOP(1) * FROM @Job_ID_Table)

    -- ########################################
    -- #     Step 1: Backup the database.     #
    -- ########################################

    -- Step Name 
    DECLARE @BackupDatabaseStepName sysname
    SET @BackupDatabaseStepName = NULL
    SET @BackupDatabaseStepName = 'Backup ' + @DbName

    -- Create Step
    DECLARE @BackupDatabaseStep nvarchar(max)
    SET @BackupDatabaseStep = NULL
    SET @BackupDatabaseStep = 
    'USE msdb; 
     EXEC sp_add_jobstep @job_id = N''' + CONVERT(nvarchar(max), @Job_ID) +''', @step_name = N''' + @BackupDatabaseStepName + ''', @subsystem = N''TSQL'', @command = N''
        DECLARE @BackupFilePath nvarchar(max)
        SET @BackupFilePath = ''''' + @BackupPathName + @DbName + ''''' + ''''.'''' + 
            /*Year */   convert(varchar(4), DATEPART(yyyy, GETDATE())) + ''''-'''' + 
            /*Month*/   right(''''00'''' + convert(varchar(2), DATEPART(mm, GETDATE())),2) + ''''-'''' + 
            /*Day  */   right(''''00'''' + convert(varchar(2), DATEPART(dd, GETDATE())),2) + ''''-'''' + 
            /*Hour */   right(''''00'''' + convert(varchar(2), DATEPART(hh, GETDATE())),2) + ''''-'''' + 
            /*Min  */   right(''''00'''' + convert(varchar(2), DATEPART(mi, GETDATE())),2) + ''''.BAK''''
        DECLARE @BackupScript nvarchar(max)
        SET @BackupScript = ''''BACKUP DATABASE ' + @DbName + ' TO DISK = '''''''''''' + @BackupFilePath + ''''''''''''''''
        EXEC (@BackupScript) /* Have to execute this this way because BACKUP DATABASE doesnt allow variables. */
        SELECT @BackupFilePath
     '', @on_success_action = 3, @retry_attempts = 5, @retry_interval = 1
    '

    -- Add step to Job
    EXEC sp_executesql @statement = @BackupDatabaseStep

    -- ########################################
    -- #     Step 2: Zip the database.        #
    -- ########################################

    -- Step Name 
    DECLARE @ZipDatabaseStepName sysname
    SET @ZipDatabaseStepName = NULL
    SET @ZipDatabaseStepName = 'Compress ' + @DbName

    -- Create Step
    DECLARE @ZipDatabaseStep nvarchar(max)
    SET @ZipDatabaseStep = NULL
    SET @ZipDatabaseStep = 
    'USE msdb; 
     EXEC sp_add_jobstep @job_id = N''' + CONVERT(nvarchar(max), @Job_ID) +''', @step_name = N''' + @ZipDatabaseStepName + ''', @subsystem = N''TSQL'', @command = N''
        DECLARE @BackupFilePath nvarchar(max)
        SET @BackupFilePath = ''''' + @BackupPathName + @DbName + ''''' + ''''.'''' + 
            /*Year */   convert(varchar(4), DATEPART(yyyy, GETDATE())) + ''''-'''' + 
            /*Month*/   right(''''00'''' + convert(varchar(2), DATEPART(mm, GETDATE())),2) + ''''-'''' + 
            /*Day  */   right(''''00'''' + convert(varchar(2), DATEPART(dd, GETDATE())),2) + ''''-'''' + 
            /*Hour */   right(''''00'''' + convert(varchar(2), DATEPART(hh, GETDATE())),2) + ''''-'''' + 
            /*Min  */   right(''''00'''' + convert(varchar(2), DATEPART(mi, GETDATE())),2) + ''''.BAK''''
        DECLARE @ZipFilePath nvarchar(max)
        SET @ZipFilePath = @BackupFilePath + ''''.7z''''
        DECLARE @CompressionScript nvarchar(1000) /* xp_cmdshell wont accept a varchar with max length */
        SET @CompressionScript = ''''' + @7z_path + '\7za a ' + @7zAlgorithm + ' ' + @CompressionLevel + ' ' + ''''' + @ZipFilePath + '''' '''' + @BackupFilePath + '''' ''''
        EXEC xp_cmdshell @CompressionScript
     '', @retry_attempts = 5, @retry_interval = 1
    '

    -- Add step to Job
    EXEC sp_executesql @statement = @ZipDatabaseStep

    -- Set Job Server
    DECLARE @SetJobServer nvarchar(max)
    SET @SetJobServer = 
    'USE msdb; 
     EXEC dbo.sp_add_jobserver @job_id = N''' + CONVERT(nvarchar(max), @Job_ID) + ''', @server_name = N''' + @ServerName + ''';
    '

    -- Set the Job server
    EXEC sp_executesql @statement = @SetJobServer

    SET @Iter = @Iter + 1
END

SET NOCOUNT OFF

1 个答案:

答案 0 :(得分:1)

从未找到过将值传递到服务器代理作业的更好方法,因此只是坚持创建临时表并保持作业打开并启动其他作业。