我正在尝试编写一个 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;