henhen
henhen

Reputation: 33

SQL server jobs history - job execution id?

I'm trying to figure out how SQL server groups their job history hierarchy to relate an outcome to all job steps. I'm using a data visualization tool to track errors in a dashboard, but the whole (Job outcome) step is driving me crazy.

Is there no ID links all the steps in a given job execution? I suppose that the instance_id + max(step_id) gives the instance_id of the step_id = 0 (the Job outcome). Given that the log file viewer has the results in an expandable hierarchy, I figure there must be some consistent way to represent that hierarchy in the database.

Using the job_id + run_date would work on jobs that only happen once a day where all steps are completed the same day, but when jobs run multiple times a day that breaks down.

Basically I want to join the job history table to itself where I have the job outcome for the job execution joined to each step so I could build a hierarchy like the one seen in the log viewer in my visualization tool.

Log viewer example image:

enter image description here

Any ideas?

I found the solution, the key is that the steps will be within the job start time and the job run duration:

`

select *
from
(
select sjh.run_date job_run_date
    , jobs.name job_name
    ,dbo.agent_datetime(sjh2.run_date,sjh2.run_time) job_start_time
    ,CASE sjh2.run_status WHEN 0 THEN 'Job Failed' WHEN 1 THEN 'Job Succeeded' END job_status
    ,sjh2.message job_message
    ,STUFF(STUFF(STUFF(RIGHT(REPLICATE('0', 8) + CAST(sjh2.run_duration as varchar(8)), 8), 3, 0, ':'), 6, 0, ':'), 9, 0, ':') 'job_run_duration'
    , sjh.step_id
    , sjh.step_name
    ,dbo.agent_datetime(sjh.run_date,sjh.run_time) step_run_time
    ,CASE sjh.run_status WHEN 0 THEN 'Step Failed' WHEN 1 THEN 'Step Succeeded' END step_status
    ,sjh.message step_message
    ,STUFF(STUFF(STUFF(RIGHT(REPLICATE('0', 8) + CAST(sjh.run_duration as varchar(8)), 8), 3, 0, ':'), 6, 0, ':'), 9, 0, ':') 'step_run_duration'
--  , *
from sysjobhistory sjh
join sysjobs jobs on jobs.job_id = sjh.job_id
join sysjobhistory sjh2 on sjh2.run_date = sjh.run_date 
                       and sjh2.job_id = sjh.job_id 
                       and sjh2.step_id = 0
                       and sjh.run_time >= sjh2.run_time
                       and sjh.run_time <= sjh2.run_time + sjh2.run_duration
) t1
order by job_run_date desc, job_name desc, job_start_time, step_id

`

Upvotes: 3

Views: 2934

Answers (0)

Related Questions