SQL Agent job failure history and last run status
SQL ServerSQL AgentCommand
-- Job steps that failed / were cancelled in the last 24 hours:
SELECT j.name AS job_name, h.step_id, h.step_name,
msdb.dbo.agent_datetime(h.run_date, h.run_time) AS run_at,
STUFF(STUFF(RIGHT('000000' + CAST(h.run_duration AS VARCHAR(6)), 6), 3, 0, ':'), 6, 0, ':') AS duration_hhmmss,
CASE h.run_status WHEN 0 THEN 'Failed' WHEN 1 THEN 'Succeeded' WHEN 2 THEN 'Retry'
WHEN 3 THEN 'Canceled' WHEN 4 THEN 'In progress' END AS status,
h.sql_message_id, h.sql_severity,
LEFT(h.message, 500) AS message
FROM msdb.dbo.sysjobhistory h
JOIN msdb.dbo.sysjobs j ON j.job_id = h.job_id
WHERE h.run_status IN (0, 3)
AND msdb.dbo.agent_datetime(h.run_date, h.run_time) >= DATEADD(HOUR, -24, GETDATE())
ORDER BY run_at DESC;
-- Each job's last outcome, running now, next run:
SELECT j.name, j.enabled,
CASE lr.run_status WHEN 0 THEN 'Failed' WHEN 1 THEN 'Succeeded' WHEN 3 THEN 'Canceled' END AS last_outcome,
lr.run_at AS last_run_at,
CASE WHEN a.start_execution_date IS NOT NULL AND a.stop_execution_date IS NULL THEN 'RUNNING' END AS running_now,
a.next_scheduled_run_date
FROM msdb.dbo.sysjobs j
LEFT JOIN msdb.dbo.sysjobactivity a
ON a.job_id = j.job_id AND a.session_id = (SELECT MAX(session_id) FROM msdb.dbo.syssessions)
OUTER APPLY (SELECT TOP (1) h.run_status, msdb.dbo.agent_datetime(h.run_date, h.run_time) AS run_at
FROM msdb.dbo.sysjobhistory h
WHERE h.job_id = j.job_id AND h.step_id = 0
ORDER BY h.instance_id DESC) lr
ORDER BY j.name;
-- Is the Agent service running:
SELECT servicename, status_desc, startup_type_desc FROM sys.dm_server_services;What it does
Shows job steps that failed or were cancelled in the last 24 hours with their error message; each job's last outcome, whether it is running now and its next scheduled run; and the Agent service state.
When to use it
In the morning check, on a backup/maintenance job alert, for "did the nightly job run", or after a failover to verify jobs run on the right replica.
Caution
Job history in msdb is limited (default 1,000 rows total, 100 per job); frequently running jobs quickly push out old failures, so raise the limit in Agent properties. The message column is truncated at 4,000 characters; define an output file on the job step for long output. If the Agent service is stopped, no scheduled job runs and none reports an error. Read-only query; safe.