查找SQL代理作业的Job_State - SQL Server

时间:2011-07-27 02:25:37

标签: sql-server sql-agent-job

我使用下面的脚本来获取代理作业的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

1 个答案:

答案 0 :(得分: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