title: How to get the last run job details in SQL
body: <p>How to get the last run job details in SQL Server Agent using SQL including the step details only for the last run job (not the job outcome) as i want to display this in an application </p>
  
  <p>Please help been stuck on this for ages</p>
  
  <p>This is the code I have been using below, this brings back all steps for all Jobs in the Job History,</p>
  
  <p>However, I just want to see the steps from the <strong>last</strong> run job</p>
  
  <p>thanks</p>
  
  <pre><code>USE msdb
  Go 
  SELECT j.name JobName,h.step_name StepName, 
  CONVERT(CHAR(10), CAST(STR(h.run_date,8, 0) AS dateTIME), 111) RunDate, 
  STUFF(STUFF(RIGHT('000000' + CAST ( h.run_time AS VARCHAR(6 ) ) ,6),5,0,':'),3,0,':') RunTime, 
  h.run_duration StepDuration,
      case h.run_status when 0 then 'Failed'
      when 1 then 'Succeeded' 
      when 2 then 'Retry' 
      when 3 then 'Cancelled' 
      when 4 then 'In Progress' 
  end as ExecutionStatus, 
  h.message MessageGenerated
  FROM sysjobhistory h 
  inner join sysjobs j
  ON j.job_id = h.job_id
  
      LEFT JOIN (
                  SELECT 
                      [job_id]
                      , [run_date]
                      , [run_time]
                      , [run_status]
                      , [run_duration]
                      , [message]
                      , ROW_NUMBER() OVER (
                                              PARTITION BY [job_id] 
                                              ORDER BY [run_date] DESC, [run_time] DESC
                        ) AS RowNumber
                  FROM [msdb].[dbo].[sysjobhistory]
                  WHERE [step_id] = 0
              ) AS [sJOBH]
              ON j.[job_id] = [sJOBH].[job_id]
              AND [sJOBH].[RowNumber] = 1
  
  where j.job_id = 'F04E5D3B-C873-448A-805C-C6309A92DAEC'
  
  ORDER BY j.name, h.run_date, h.run_time desc
  GO
  </code></pre>