Press "Enter" to skip to content

Enable or disable jobs

I administer SQL Servers that have several log shipping jobs, enough that manually disabling & enabling them (e.g. for maintenance windows) is tedious & time consuming. Instead, I use the following script, setting the variable @enabled to 0 or 1 to disable or enable jobs.

The list inserted into #Jobs can be amended to disable or enable other jobs as required.

USE msdb
GO

SET NOCOUNT ON;

DECLARE @enabled TINYINT
  ,@status TINYINT
  ,@i TINYINT
  ,@n TINYINT
  ,@jobname NVARCHAR(128);

/*********************** SET THIS VARIABLE ***********************/
SET @enabled = 0;  -- SET to 0 to disable or 1 to enable.
/*********************** SET THIS VARIABLE ***********************/

-- Don't proceed if @enabled is set to anything other than 0 or 1.
IF @enabled NOT IN (0, 1)
  OR @enabled IS NULL
BEGIN
  PRINT '@enabled is set to something other than 0 or 1. Terminating execution.'
  RETURN
END

-- Get list of jobs to enable/disable
IF OBJECT_ID('tempdb..#Jobs') IS NOT NULL
  DROP TABLE #Jobs;

CREATE TABLE #Jobs (
  [Id] TINYINT NOT NULL IDENTITY(1, 1)
  ,[JobName] NVARCHAR(128)
);

INSERT INTO #Jobs ([JobName])
SELECT [name]
FROM [dbo].[sysjobs]
WHERE [name] LIKE '%log shipping%'
  AND [enabled]  @enabled;

IF NOT EXISTS (SELECT * FROM #Jobs)
BEGIN
  PRINT 'There are no jobs in the list. Check that @enabled is set correctly.'
END
ELSE
BEGIN
  -- Loop through job list
  SET @i = 1;
  SET @n = (SELECT MAX([Id]) FROM #Jobs);

  WHILE @i <= @n
  BEGIN
    -- Get job name
    SET @jobname = (
      SELECT [JobName]
      FROM #Jobs
      WHERE [Id] = @i
    );

    -- Disable or enable job
    EXEC [dbo].[sp_update_job]
      @job_name = @jobname,
      @enabled = @enabled;

    -- Check current status & return result
    SET @status = (
      SELECT [enabled]
      FROM [dbo].[sysjobs]
      WHERE [name] = @jobname
    );

    IF @status = 0
    BEGIN
      PRINT N'"' + @jobname + N'" job has been disabled.'
    END
    ELSE IF @status = 1
    BEGIN
      PRINT N'"' + @jobname + N'" job has been enabled.'
    END

    SET @i += 1;
  END

  PRINT CHAR(13) + CHAR(10)
    + 'Refresh the job list to verify that all log shipping jobs have been disabled or enabled as expected.'
END

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *