USE msdb;
GO

PRINT '================================================================================';
PRINT 'SECTION 1: SQL AGENT JOB STATUS';
PRINT '================================================================================';
GO

-- List all jobs in SQL Agent
SELECT name AS JobName, enabled, date_created, date_modified
FROM msdb.dbo.sysjobs
ORDER BY name;
GO

-- Job schedule summary
SELECT j.name AS JobName, s.name AS ScheduleName,
       s.enabled, s.freq_type, s.active_start_date, s.active_start_time
FROM msdb.dbo.sysjobs j
JOIN msdb.dbo.sysjobschedules js ON j.job_id = js.job_id
JOIN msdb.dbo.sysschedules s ON js.schedule_id = s.schedule_id
ORDER BY j.name;
GO

-- Last job run details
SELECT j.name AS JobName,
       h.run_status,
       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 StatusDescription,
       msdb.dbo.agent_datetime(h.run_date, h.run_time) AS RunDateTime,
       h.run_duration
FROM dbo.sysjobs j
LEFT JOIN dbo.sysjobhistory h ON j.job_id = h.job_id
WHERE h.instance_id IN (
    SELECT MAX(instance_id) FROM dbo.sysjobhistory GROUP BY job_id
)
ORDER BY RunDateTime DESC;
GO