我正在尝试在 MS SQL Server 中获取我的作业状态,目的是在我们的远程监控软件中创建警报,如果任何已启用的作业出错。
目前我正在使用 sys.xp_sqlagent_enum_jobs 存储过程,但是它似乎同时显示了启用和禁用的作业,所以我尝试使用 msdb.dbo.sp_help_job,这正是我需要的,但没有使用 OPENQUERY 参数(在服务器)由于嵌套错误,我无法查询或捕获结果,我得到了与 sp_get_composite_job_info 相同的结果。
所以我开始没有想法了,有没有人知道一种方法来捕获此信息以供查询或存储在以后查询的能力中。
我将包含我当前的代码,以防它对任何人有用,它可以很好地返回失败的作业数量,但如果你有一个失败的作业被禁用,这也会显示出来。
objRecordSet.Open _
"SET NOCOUNT ON " & _
"DECLARE @MaxLength INT " & _
"SET @MaxLength = 50 " & _
"DECLARE @xp_results TABLE ( job_id uniqueidentifier NOT NULL, " & _
"last_run_date nvarchar (20) NOT NULL, " & _
"last_run_time nvarchar (20) NOT NULL, " & _
"next_run_date nvarchar (20) NOT NULL, " & _
"next_run_time nvarchar (20) NOT NULL, " & _
"next_run_schedule_id INT NOT NULL, " & _
"requested_to_run INT NOT NULL, " & _
"request_source INT NOT NULL, " & _
"request_source_id sysname " & _
"COLLATE database_default NULL, " & _
"running INT NOT NULL, " & _
"current_step INT NOT NULL, " & _
"current_retry_attempt INT NOT NULL, " & _
"job_state INT NOT NULL " & _
")" & _
"DECLARE @job_owner sysname " & _
"DECLARE @is_sysadmin INT " & _
"SET @is_sysadmin = isnull (is_srvrolemember ('sysadmin'), 0) " & _
"SET @job_owner = suser_sname () " & _
"INSERT INTO @xp_results EXECUTE sys.xp_sqlagent_enum_jobs @is_sysadmin, @job_owner " & _
"UPDATE @xp_results SET last_run_time = right ('000000' + last_run_time, 6), next_run_time = right ('000000' + next_run_time, 6) " & _
"SELECT count(*) as cnt FROM @xp_results x LEFT JOIN msdb.dbo.sysjobs j ON x.job_id = j.job_id LEFT OUTER JOIN msdb.dbo.syscategories c " & _
"ON j.category_id = c.category_id LEFT OUTER JOIN msdb.dbo.sysjobhistory h ON x.job_id = h.job_id " & _
"AND x.last_run_date = h.run_date AND x.last_run_time = h.run_time AND h.step_id = 0 where h.run_status = 0 ", _
objConnection, adOpenStatic, adLockOptimistic
message = message & "JOBCHECK#" & objRecordSet("cnt") & vbNewLine