我需要创建一个获取sql server agent作业状态的查询。
棘手的部分是,我都希望上次失败的时间(如果有的话)和上次成功的时间 - 这可能吗?
到目前为止,我只能获得最后一次成功的运行或最后一次失败的工作。
SELECT
job.name
,jobh.run_date
,DATEADD(HOUR, (jobh.run_time / 1000000) % 100,
DATEADD(MINUTE, (jobh.run_time / 10000) % 100,
DATEADD(SECOND, (jobh.run_time / 100) % 100,
DATEADD(MILLISECOND, (jobh.run_time % 100) * 10,
cast('00:00:00' as TIME(0)))))) AS 'tidspunkt'
,jobh.run_duration
FROM msdb.dbo.sysjobhistory jobh
JOIN [msdb].[dbo].[sysjobs] job ON jobh.job_id = job.job_id
WHERE jobh.step_id = 0
AND jobh.message LIKE '%failed%'
AND (jobh.run_date = CONVERT(VARCHAR, GETDATE(), 112) OR jobh.run_date = CONVERT(VARCHAR, DATEADD(DAY, -1, GETDATE()), 112) )
AND job.name = 'UpdateCPR'
ORDER BY jobh.run_date DESC, jobh.run_time DESC
答案 0 :(得分:2)
只需更改行......
AND jobh.message LIKE '%failed%'
...跟随......
AND (jobh.message LIKE '%failed%' OR jobh.message LIKE '%succeeded%')
您将获得多行。如果您愿意,可以通过LIKE结果对其进行分组,并从两者中选择TOP 1以在一行中检索它。
修改强>
使用此功能可以将失败和成功信息放在一行中。
;WITH jobRuns AS (
SELECT
job.job_id,
job.name,
jobh.run_time,
jobh.run_duration,
execStatus
FROM msdb.dbo.sysjobhistory jobh
JOIN msdb.dbo.sysjobs job
ON jobh.job_id = job.job_id
CROSS APPLY(
SELECT execStatus = CASE
WHEN jobh.message LIKE '%failed%' THEN 0
WHEN jobh.message LIKE '%succeeded%' THEN 1 END) ext
WHERE
jobh.step_id = 0
and job.name LIKE '%testjob%'
/*GROUP BY
job.job_id,
job.name,
jobh.run_time,
execStatus*/)
,lastRuns AS (
SELECT TOP 1
jobRuns.job_id,
jobRuns.name,
run_time_failed = failed.run_time,
run_duration_failed = failed.run_duration,
run_time_succeeded = success.run_time,
run_duration_succeeded = success.run_duration
FROM jobRuns
CROSS APPLY(
SELECT TOP 1 run_time, run_duration
FROM jobRuns
WHERE execStatus = 0
ORDER BY run_time DESC) failed
CROSS APPLY(
SELECT TOP 1 run_time, run_duration
FROM jobRuns
WHERE execStatus = 1
ORDER BY run_time DESC) success
)
SELECT *
FROM lastRuns