Using SQLAgent Tokens – Automatically add a schedule

Automatically add a schedule to a SQL Agent job. This example adds one that will run two hours from now, once. Left to do: what if no longer today?

More tokens.

DECLARE @vcSchedule VARCHAR(128),
   
@nJOBID uniqueidentifier,
   
@nDATE INT,
   
@nTIME INT,
   
@nHours INT
SELECT 
@vcSchedule 'Reschedule',
   
@nJOBID CONVERT(uniqueidentifier[JOBID]),
   
@nDATE [DATE],
   
@nTIME [TIME],
   
@nHours '020000' @nTIME
--SELECT @nJOBID, @nDATE, @nTIME, @nHours 

IF EXISTS (SELECT [name] FROM [msdb].[dbo].[sysjobschedules] WHERE job_id @nJOBID AND name@vcSchedule)
  
EXEC msdb..sp_delete_jobschedule @job_id=@nJOBID@name=@vcSchedule

EXECUTE msdb.dbo.sp_add_jobschedule 
   
@job_id @nJOBID
   
@name @vcSchedule@enabled 1
   
@freq_type 1
   
@active_start_date @nDATE
   
@active_start_time @nHours
   
@freq_interval 1--once
   
@freq_subday_type 1--At the specified time
   
@freq_subday_interval 1
   
@freq_relative_interval 0
   
@freq_recurrence_factor 0
   
@active_end_date 99991231
   
@active_end_time 235959

Comments are closed.

Post Navigation