Listing Unsuccessful Jobs in the Last 24 Hours in SQL Server
Hello to everyone,
In this article, I will try to give information about listing unsuccessful jobs in SQL Server in the last 24 hours.
In SQL Server, in some cases, you may want to list unsuccessful Jobs in the Last 24 Hours.
You can easily do this using the code below.
Code 1
DECLARE @FinalDate INT;
SET @FinalDate = CONVERT(INT, CONVERT(VARCHAR(10), DATEADD(DAY, -1, GETDATE()), 112)); -- Yesterday's date as Integer in YYYYMMDD format
SELECT j.[name],
s.step_name,
h.step_id,
h.step_name,
h.run_date,
h.run_time,
h.sql_severity,
h.message,
h.server
FROM msdb.dbo.sysjobhistory h
INNER JOIN msdb.dbo.sysjobs j
ON h.job_id = j.job_id
INNER JOIN msdb.dbo.sysjobsteps s
ON j.job_id = s.job_id
AND h.step_id = s.step_id
WHERE h.run_status = 0 -- Failure
AND h.run_date > @FinalDate
ORDER BY h.instance_id DESC;
Code 2
SELECT msdb.dbo.agent_datetime(jh.run_date, jh.run_time) AS date_time,
j.name AS job_name,
js.step_id AS job_step,
jh.message AS error_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
AND jh.step_id = js.step_id
WHERE jh.run_status = 0
AND msdb.dbo.agent_datetime(jh.run_date, jh.run_time) >= GETDATE() - 1
ORDER BY msdb.dbo.agent_datetime(jh.run_date, jh.run_time) DESC;
Good luck to everyone in business and life.