长期工作

时间:2012-08-01 15:26:43

标签: sql tsql

我不确定发生了什么事?即使作业在晚上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 

1 个答案:

答案 0 :(得分: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)