dumping ground for code that might be useful sometime, somewhere. Beware the formatting mangle of the blog post...

Monday, March 5, 2007

TSQL: SQLServerAgent job history

Cheap and cheerful summary of most recent run of jobs. Note the comments before --create. Those are required for me to post the code, if I start with the c-word I get a page error.

--create table #tbl
(
instance_id int ,
job_id uniqueidentifier ,
job_name sysname ,
step_id int ,
step_name sysname ,
sql_message_id int ,
sql_severity int ,
message nvarchar(1024) ,
run_status int ,
run_date char(8) ,
run_time char(23) ,
run_duration int ,
operator_emailed nvarchar(20) ,
operator_netsent nvarchar(20) ,
operator_paged nvarchar(20) ,
retries_attempted int ,
server nvarchar(30)
)
insert #tbl
exec msdb.dbo.sp_help_jobhistory @mode = 'FULL'
GO

--format our date and time
--add leading zeroes
update #tbl
set run_time =
CASE len(run_time)
WHEN 6 THEN run_time
WHEN 5 THEN '0' + run_time
WHEN 4 THEN '00' + run_time
WHEN 3 THEN '000' + run_time
WHEN 2 THEN '0000' + run_time
WHEN 1 THEN '00000' + run_time
else 'wibble'
end
--add colons
update #tbl
set run_time = run_date + ' ' + STUFF(STUFF(ltrim(rtrim(run_time)), 3, 0, ':'), 6, 0, ':') + ':000'

select
max(instance_id) as instance_id
into
#tbl2
from
#tbl
where
step_id = 0
group by
job_name

select #tbl.* from #tbl
inner join #tbl2 on #tbl.instance_id = #tbl2.instance_id

drop table #tbl
drop table #tbl2

No comments: