Question

I am creating some jobs to backup my databases and then compress them. I want to backup the database in one step and zip the file in the next step, so I want to pass the name for the file from the first step to the second. Does anyone know how I should be passing variables between steps?

I know I could put this all in one step, or that I could not have the time in the file name to make this work, but I would like to keep the date and time in the backup file names and I would like to keep the steps separate so it is easier to see why backups fail when they fail.

If saving values into a temp table is the only way to do this I can do that but I thought there should be a better way than that.

I am running this on MS SQL 2005 and 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
Was it helpful?

Solution

Never found a better way to pass values into server agent jobs so just stuck to creating a temp table and holding the job open and starting other jobs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top