1

我不确定发生了什么?即使作业在晚上 11:50 停止运行,我仍然收到一封电子邮件,这显然不到 7 小时,因为它从昨晚 7 点开始。如果作业运行时间超过 7 小时,应该给我发电子邮件,并且出于某种原因,昨天它在测试中有效,但今天它不是……有什么想法吗?

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 
4

1 回答 1

2

您的查询的问题在于它只检查自作业开始以来已经过去了多长时间......它没有考虑作业何时完成。

如果在 7 小时内没有其他作业执行,那么您将查询限制为最近运行的检查不会排除先前完成的作业......然后您的查询将返回 7 小时前开始的作业,但在这种情况下,在 4 小时内完成。

要修复您的查询以排除已完成的作业,请按如下方式修改您的查询:

SELECT *
FROM 
    msdb..sysjobactivity aj
    JOIN msdb..sysjobs sj on sj.job_id = aj.job_id
WHERE 
    DATEDIFF(HOUR, aj.start_execution_date, 
            ISNULL(aj.stop_execution_date, GetDate()) )> 7 
    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)
于 2012-08-01T15:36:57.843 回答