Tuesday, December 18, 2007

Capturing SQL Agent Job Information

The following query will pull selected data from the sp_help_job stored procedure and put it into the requested table:

USE msdb

IF OBJECT_ID('tempdb..#TmpJobs') IS NOT NULL
DROP TABLE #TmpJobs

SELECT *
INTO #TmpJobs
FROM OPENROWSET('sqloledb'
, 'server=(local);trusted_connection=yes'
, 'set fmtonly off exec msdb.dbo.sp_help_job')

SELECT originating_server, name, enabled, owner, last_run_date, last_run_outcome, next_run_date
INTO Database..Table

FROM #TmpJobs

This comes in very handy if you want to use a DTS package to grab this data from multiple servers and populate one table that you can query. I am using this in correlation with a truncate command for the table so that a select * will get me only the current data, since historical information is already kept in each server's individual msdb database.

Note: In SQL2005 you will have to have the sp_configure parameter Ad Hoc Distributed Queries enabled.