Skip SQL job execution on last day OR specific day of the month.

A few days before I got the requirement to schedule a job in a way that it should not run on the last day of the month. and as we know, in SQL job schedule we do not have any option to skip the job execution on a specific day. 

But, we could able to achieve this using T-SQL. Below is the SQL which i have used to fulfill the requirement. 


USE MSDB

DECLARE @date as datetime;

SET @date=(select convert(date,dateadd(s,-1,dateadd(mm,datediff(m,0,getdate())+1,0)))) -- Getting last day of the month

IF(dateadd(dd,0,DATEDIFF(dd,0,GETDATE()))=@date)  -- Comparing last day of the month with current date.

begin

exec sp_stop_job @job_name='<Job_Name>'  -- If condition satisfied then, job execution will stop

end

else

begin

exec sp_update_jobstep @job_name='<Job_Name>',@step_id=2 -- If condition is not satisfied then, job execution will proceed further.

end

We can add the above query as the first step in SQL job or a separate job can be created which would call another job. 

Have you ever got such a requirement? if yes then let me know what strategy you used? 

Comments

Popular posts from this blog

What is DACPAC and how to use it?

Backdoor in SQL server. Is this hacking, loop hole or Feature ?

Always on setup end to end - Part 1 || Pre-requisites