I am not sure what is going on? I still get an email even though the job stopped running at 11:50 pm which clearly is less than thean 7 hours being that it started at 7 pm last night..It is suppose to email me if the job runs longer than 7 hours and for some reason yesterday it worked in test but today its not..Any ideas???
SELECT *
FROM msdb..sysjobactivity aj
JOIN msdb..sysjobs sj on sj.job_id = aj.job_id
WHERE DATEDIFF(HOUR,aj.start_execution_date,GetDate())> 7
AND aj.start_execution_date IS NOT NULL
AND sj.name = 'Nightly_Job'
and not exists ( -- make sure this is the most recent run
select 1
from msdb..sysjobactivity new
where new.job_id = aj.job_id
and new.start_execution_date > aj.start_execution_date)
if @@ROWCOUNT > 0
BEGIN
USE msdb
EXEC sp_send_dbmail
@profile_name = 'DB_Mail',
@recipients = 'xxx@yyy.com',
@subject = 'T-SQL Query Result',
@body = 'The Nightly_Job has been running 7
The problem with your query is that it only checks how long has passed since the job was started… it doesn’t take into account when the job completed.
If there are no other executions of the job within 7 hours, then your check that limits the query to the most recent run doesn’t exclude the previously completed job… your query then returns the job that was started over 7 hours ago, but in this case completed within 4 hours.
To fix your query to exclude completed jobs, modify your query as follows: