可能在房屋周围一些,但能解决问题
;WITH cJobDetail AS (
SELECT
ja.job_id
,j.name
,ja.start_execution_date
,ja.last_executed_step_id
--,j.start_step_id
,CASE
WHEN j.start_step_id = COALESCE(ja.last_executed_step_id,j.start_step_id) THEN j.start_step_id
ELSE NULL
END AS ExecutingStepId
,ja.job_history_id
,DATEDIFF(HOUR, ja.start_execution_date, COALESCE(ja.stop_execution_date,SYSDATETIME())) AS JobHourRunning
,DATEDIFF(SECOND, ja.start_execution_date, COALESCE(ja.stop_execution_date,SYSDATETIME())) / 60 % 60 AS JobMinuteRunning
,DATEDIFF(SECOND, ja.start_execution_date, COALESCE(ja.stop_execution_date,SYSDATETIME())) % 60 AS JobSecondRunning
FROM dbo.sysjobactivity ja
INNER JOIN dbo.sysjobs j
ON ja.job_id = j.job_id
WHERE ja.start_execution_date IS NOT NULL
AND ja.stop_execution_date IS NULL
)
,MaxJobHistoryStepStatus AS (
SELECT jh.job_id, jh.step_id, MAX(jh.instance_id) AS MaxInstanceId
FROM cJobDetail jd
INNER JOIN dbo.sysjobhistory jh
ON jd.job_id = jh.job_id
AND jd.last_executed_step_id = jh.step_id
GROUP BY jh.job_id, jh.step_id
)
SELECT
jd.job_id
,jd.name
,jd.start_execution_date
,COALESCE(
CASE jh.run_status
WHEN 1 THEN
CASE js.on_success_action
WHEN 3 THEN jd.last_executed_step_id + 1
WHEN 4 THEN js.on_success_step_id
END
WHEN 0 THEN
CASE js.on_fail_action
WHEN 3 THEN jd.last_executed_step_id + 1
WHEN 4 THEN js.on_fail_step_id
END
END,jd.ExecutingStepId) AS StepId
,jd.JobHourRunning
,jd.JobMinuteRunning
,jd.JobSecondRunning
FROM cJobDetail jd
LEFT JOIN MaxJobHistoryStepStatus mhs
ON jd.job_id = mhs.job_id
LEFT JOIN dbo.sysjobhistory jh
ON mhs.MaxInstanceId = jh.instance_id
LEFT JOIN dbo.sysjobsteps js
ON mhs.job_id = js.job_id
AND mhs.step_id = js.step_id