0

我正在使用下面的脚本来获取代理作业的 Job_state。

当作业正在运行时,它返回 1 作为 job_state => 这很好。

但是对于所有其他情况(失败/成功/取消),它返回 job_status 4(这意味着它的空闲)

如何获得准确的 job_state 以便确定它是失败/成功还是取消。

到目前为止我的脚本:

DECLARE @xp_results TABLE
(
  job_id UNIQUEIDENTIFIER NOT NULL ,
  last_run_date INT NOT NULL ,
  last_run_time INT NOT NULL ,
  next_run_date INT NOT NULL ,
  next_run_time INT 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
)      
SET NOCOUNT ON
INSERT  INTO @xp_results
    EXEC master.dbo.xp_sqlagent_enum_jobs 1, ''

DECLARE @jobs TABLE
(
  rownum INT IDENTITY(1, 1)
             PRIMARY KEY
             NOT NULL ,
  job_id UNIQUEIDENTIFIER NOT NULL
)

SELECT  name,job_state
FROM    @xp_results rj
    INNER JOIN msdb.dbo.sysjobs sj ON sj.job_id = rj.job_id
4

1 回答 1

0

我解决了这个问题,如下所示。应该有其他好的方法来做到这一点。

DECLARE @xp_results TABLE
(
  job_id UNIQUEIDENTIFIER NOT NULL ,
  last_run_date INT NOT NULL ,
  last_run_time INT NOT NULL ,
  next_run_date INT NOT NULL ,
  next_run_time INT 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
)      
SET NOCOUNT ON
INSERT  INTO @xp_results
    EXEC master.dbo.xp_sqlagent_enum_jobs 1, ''

DECLARE @jobs TABLE
(
  rownum INT IDENTITY(1, 1)
             PRIMARY KEY
             NOT NULL ,
  job_id UNIQUEIDENTIFIER NOT NULL
)
DROP TABLE #temp    
exec sp_serveroption 'hts0519', 'data access', 'true'
select * 
INTO #temp
FROM OPENQUERY( hts0519, ' EXEC msdb.dbo.sp_help_job')

SELECT  sj.name,

    CASE job_state WHEN 4 THEN 'IDLE' ELSE 'RUNNING' END AS CURRENT_STATUS, 
    CASE tmp.last_run_outcome
        WHEN 0 THEN 'FAILED'
        WHEN 1 THEN 'SUCCEEDED'
        WHEN 3 THEN 'CANCELED'
        WHEN 5 THEN 'UNKNOWN'   
    END  AS LAST_OUTCOME
 FROM    @xp_results rj
    INNER JOIN msdb.dbo.sysjobs sj ON sj.job_id = rj.job_id
    INNER JOIN #temp tmp ON sj.name = tmp.name
于 2011-07-27T03:06:25.777 回答