HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

How to stop a job for the rest of the day after the relevant condition has been satisfied once?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
afterrestoncetheconditionbeenstophasrelevantday

Problem

I have a job that runs every 5 minutes to check an IF condition. If the condition is true, it will send an email, if not, it won’t do anything.

My problem is that once the IF condition is true, it will remain true for the whole day and, as the job is running after every 5 minutes, it will keep sending the email after every 5 minutes.

I need to stop the job for the whole day once the email has been sent once. Is there a way to do so?

Solution

I actually wrote a similar tip at mssqltips.com.
For your current case, the general idea would be like this:

-
you may add an additional step at the end of the job, once your primary job steps succeed, the job will run the final step (i.e. the newly added step)

-
If your job fails in your primary steps, your job will just exit and no need to run the final added step.

-
In you final job step, you will do one thing, i.e. updating your job schedule' start date to be next day.

use msdb

declare @active_date int, @sch_name varchar(128);

select @sch_name=s.name
from msdb.dbo.sysschedules s
inner join msdb.dbo.sysjobschedules js
on js.schedule_id = s.schedule_id
and js.job_id = $(ESCAPE_NONE(JOBID));

set @active_date = cast(replace(cast(cast(getdate()+1 as date) as varchar(10)), '-', '') as int);

exec sp_update_schedule @name=@sch_name, @active_start_date= @active_date;


Of course, I assume your job has one dedicated schedule only.
The approach is all self-dependent and you do not need any additional external jobs to manage your current job.

Code Snippets

use msdb

declare @active_date int, @sch_name varchar(128);

select @sch_name=s.name
from msdb.dbo.sysschedules s
inner join msdb.dbo.sysjobschedules js
on js.schedule_id = s.schedule_id
and js.job_id = $(ESCAPE_NONE(JOBID));

set @active_date = cast(replace(cast(cast(getdate()+1 as date) as varchar(10)), '-', '') as int);

exec sp_update_schedule @name=@sch_name, @active_start_date= @active_date;

Context

StackExchange Database Administrators Q#229664, answer score: 2

Revisions (0)

No revisions yet.