报告失败的SQL代理作业

时间:2016-02-09 06:11:05

标签: sql-server tsql common-table-expression sql-agent

我正在尝试编写一个SQL Server查询,该查询将返回最近XX分钟/天等的失败作业。

对于每个失败的作业,我基本上都想要一条记录,并且每个步骤的消息都是串联的。我写了下面的查询,但是由于分组,我得到一个连贯的消息为整个工作,而不仅仅是这个特定的实例 - 我无法解决它。任何帮助将不胜感激:)

WITH    failedJobs
          AS ( SELECT   j.name ,
                        DATEADD(SECOND,
                                ( run_time / 10000 ) * 3600 + ( ( run_time - ( ( run_time / 10000 ) * 10000 ) ) / 100 )
                                * 60 + run_time - ( ( run_time / 100 ) * 100 ),
                                CONVERT(DATETIME, CONVERT(VARCHAR(8), run_date), 105)) AS run_datetime ,
                        js.step_name ,
                        jh.job_id ,
                        jh.step_id ,
                        jh.instance_id ,
                        jh.sql_severity ,
                        jh.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
               WHERE    jh.run_status = 0)
     SELECT fj.job_id ,
            STUFF(( SELECT  CHAR(10) + message
                    FROM    failedJobs fj2
                    WHERE   fj.job_id = fj2.job_id
                  FOR
                    XML PATH('') ), 1, 1, '') AS message
     FROM   failedJobs fj
     WHERE  DATEDIFF(DAY, run_datetime, GETDATE()) <= 2 -- Last 2 days
     GROUP BY fj.job_id; 

0 个答案:

没有答案