Considerations
- I need to create a Dashboard with job failure AND running jobs.
- I have a code to get
run_status
etc. - I am not interested in succeed jobs.
- I extract failure from
run_status = 0
.
Query as of today:
select
j.name as 'JobName',run_date, run_time, run_status,
msdb.dbo.agent_datetime(run_date, run_time) as 'RunDateTime',
run_duration,
((run_duration/10000*3600 + (run_duration/100)%100*60 + run_duration%100
+ 31 ) / 60) as 'RunDurationMinutes',
DateADD(MINUTE,((run_duration/10000*3600 + (run_duration/100)%100*60 +
run_duration%100 + 31 ) / 60) ,
msdb.dbo.agent_datetime(run_date, run_time)) as RunStopDate,
step_id, Step_name
From
msdb.dbo.sysjobs j
INNER JOIN
msdb.dbo.sysjobhistory h
ON
j.job_id = h.job_id
where
j.enabled = 1 --Only Enabled Jobs
and
msdb.dbo.agent_datetime(run_date, run_time) > DATEADD(DAY,-90, GETDATE())
- How and where do I add a case to below query? I want all my columns but also a new
execeution_status
as below. - I also assume I can get from
run_duration
the amount an on-going job has run so far.
else CASE h.execution_status WHEN j.[execution_status] = 0 THEN ' Returns only those jobs that are not idle or suspended. ' WHEN j.[execution_status] = 1 THEN 'Execution' WHEN j.[execution_status] = 2 THEN ' Waiting for thread ' WHEN j.[execution_status] = 3 THEN ' Between retries ' WHEN j.[execution_status] = 4 THEN 'Idle' WHEN j.[execution_status] = 5 THEN 'Suspenden' WHEN j.[execution_status] = 7 THEN 'Performing complet actions' End AS ExecutionStatus,
Source execution_status
: https://learn.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-help-job-transact-sql.
We did came up with this simple solution, and I want some feedback about pros and cons.
SELECT ja.session_id, ja.job_id, j.name AS job_name, CASE WHEN ja.start_execution_date IS NULL THEN 'Not running' WHEN ja.start_execution_date IS NOT NULL AND ja.stop_execution_date IS NULL THEN 'Running' WHEN ja.start_execution_date IS NOT NULL AND ja.stop_execution_date IS NOT NULL THEN 'Finished' END AS 'RunStatus' , ja.last_executed_step_id, jh.step_name, jh.run_status, ja.start_execution_date, ja.stop_execution_date, ja.job_history_id, j.[enabled] FROM (msdb.dbo.sysjobactivity ja LEFT JOIN msdb.dbo.sysjobhistory jh ON ja.job_history_id = jh.instance_id) join msdb.dbo.sysjobs_view j on ja.job_id = j.job_id WHERE session_id = (SELECT MAX(session_id) FROM msdb.dbo.sysjobactivity) and j.enabled =1