什么是查询来显示失败的SQL作业


Answers:


12

我认为您一次查询不会真正获得“所有”作业信息,因为可以将作业配置为输出文件。输出文件有时可以获得比报告或写入msdb表更多的信息。

但是,可以通过此查询拉取通过SSMS查看作业历史记录而获得的视图,以仅返回失败的作业(例如,如果一个作业有2个步骤,而第二个失败,则此查询将返回两个步骤):

select j.name
    ,js.step_name
    ,jh.sql_severity
    ,jh.message
    ,jh.run_date
    ,jh.run_time
FROM msdb.dbo.sysjobs AS j
INNER JOIN msdb.dbo.sysjobsteps AS js
   ON js.job_id = j.job_id
INNER JOIN msdb.dbo.sysjobhistory AS jh
   ON jh.job_id = j.job_id AND jh.step_id = js.step_id
WHERE jh.run_status = 0

在此处输入图片说明


6

您可以通过sql server中可用的标准报告获取此信息:

右键单击“ SQL Server代理”>“标准报告”,然后选择所需的报告,例如作业执行“失败的或花费很多时间的报告” ..根据需要选择报告:

要么,

您可以使用以下脚本查找过去24小时内失败的作业:

-- Variable Declarations 

DECLARE @PreviousDate datetime  
DECLARE @Year VARCHAR(4)   
DECLARE @Month VARCHAR(2)  
DECLARE @MonthPre VARCHAR(2)  
DECLARE @Day VARCHAR(2)  
DECLARE @DayPre VARCHAR(2)  
DECLARE @FinalDate INT  

-- Initialize Variables  
SET @PreviousDate = DATEADD(dd, -1, GETDATE()) -- Last 1 day   
SET @Year = DATEPART(yyyy, @PreviousDate)   
SELECT @MonthPre = CONVERT(VARCHAR(2), DATEPART(mm, @PreviousDate))  
SELECT @Month = RIGHT(CONVERT(VARCHAR, (@MonthPre + 1000000000)),2)  
SELECT @DayPre = CONVERT(VARCHAR(2), DATEPART(dd, @PreviousDate))  
SELECT @Day = RIGHT(CONVERT(VARCHAR, (@DayPre + 1000000000)),2)  
SET @FinalDate = CAST(@Year + @Month + @Day AS INT)  

-- Final Logic 

SELECT   j.[name],  
         s.step_name,  
         h.step_id,  
         h.step_name,  
         h.run_date,  
         h.run_time,  
         h.sql_severity,  
         h.message,   
         h.server  
FROM     msdb.dbo.sysjobhistory h  
         INNER JOIN msdb.dbo.sysjobs j  
           ON h.job_id = j.job_id  
         INNER JOIN msdb.dbo.sysjobsteps s  
           ON j.job_id = s.job_id 
           AND h.step_id = s.step_id  
WHERE    h.run_status = 0 -- Failure  
         AND h.run_date > @FinalDate  
ORDER BY h.instance_id DESC  

如果您需要信息作为报告,请使用此链接中的代码


谢谢您的提示,这正是我想要的。我认为我们可以稍微简化变量以获得相同的结果:DECLARE @FinalDate INT; -- Initialize Variables SET @FinalDate = CAST(CONVERT(VARCHAR(10), DATEADD(dd, -1, GETDATE()), 112) AS INT) -- Yesterday's date as Integer in YYYYMMDD format -- Final Logic .... no change

1

我稍稍修改了Shawn Melton的代码,以获取过去24小时内的所有工作错误。联接中缺少一条语句,我也已修复。非常感谢Shawn,好东西!


/*  Select all jobs with an error in the past 24 hours */
SELECT MSDB.dbo.agent_datetime(jh.run_date,jh.run_time) as date_time
    ,j.name as job_name,js.step_id as job_step,jh.message as error_message
    FROM msdb.dbo.sysjobs AS j
    INNER JOIN msdb.dbo.sysjobsteps AS js ON js.job_id = j.job_id
    INNER JOIN msdb.dbo.sysjobhistory AS jh ON jh.job_id = j.job_id AND jh.step_id = js.step_id
    WHERE jh.run_status = 0 AND MSDB.dbo.agent_datetime(jh.run_date,jh.run_time) >= GETDATE()-1
    ORDER BY MSDB.dbo.agent_datetime(jh.run_date,jh.run_time) DESC
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.