Ssms

如何擷取作業退出程式碼?

  • June 9, 2020

我基本上是在嘗試找到一種更好的方法來確定我的工作是否已成功完成,然後再繼續進行同一工作的另一次呼叫。在特別呼叫這個工作之前,我有多個通過解析過程執行的工作,但我不希望所有工作呼叫都發生衝突並破壞一切。我現在可以解決的問題如下:

這基本上只是檢查 job_ID 是否存在於 sys_jobs_view 和 sysjobactivity 中。如果是這樣,請等待。如果沒有,請再次中斷並執行作業。

WHILE EXISTS (SELECT
           job.Name, job.job_ID
           ,job.Originating_Server
           ,activity.run_requested_Date
           ,datediff(minute, activity.run_requested_Date, getdate()) AS Elapsed
       FROM
           msdb.dbo.sysjobs_view job 
               INNER JOIN msdb.dbo.sysjobactivity activity
               ON (job.job_id = activity.job_id)
       WHERE
           run_Requested_date is not null 
           AND stop_execution_date is null
           AND job.name like 'myJob%')
       BEGIN 
           WAITFOR DELAY '00:00:05.000'
       END 
EXEC msdb.dbo.sp_start_job 'myJob'

有沒有辦法只擷取退出程式碼並具有如下所示的內容:

虛擬碼:

WHILE (*Capture Exit code for 'myJob'* = In_Progress)
BEGIN
   WAITFOR DELAY '00:00:05.000'

   IF (*Capture Exit code for 'myJob'* = Fail)
   BEGIN
       BREAK
   END
END

IF (*Capture Exit code for 'myJob'* = Success)
BEGIN
   EXEC msdb.dbo.sp_start_job 'myJob'
END

如果您創建一個 FUNCTION 並查詢 MSDB 中的sysjobhistory表,您可以獲得關於最近作業執行的簡單響應。

創建函式:

CREATE FUNCTION [dbo].[fnGetLatestAgentJobExitCode]
(
   @JobName VARCHAR(100)
)
RETURNS VARCHAR(25)
AS
BEGIN
   RETURN(
       SELECT TOP (1)
           CASE jh.run_status
               WHEN 0 THEN 'Failed'
               WHEN 1 THEN 'Succeeded'
               WHEN 2 THEN 'Retry'
               WHEN 3 THEN 'Canceled'
               WHEN 4 THEN 'In Progress'
           END AS [Status]
       FROM [msdb].[dbo].[sysjobactivity] ja
       INNER JOIN [msdb].[dbo].[sysjobs] j ON j.job_id = ja.job_id
       INNER JOIN [msdb].[dbo].[sysjobhistory] jh ON jh.job_id = j.job_id AND jh.instance_id = ja.job_history_id
       WHERE j.[name] = @JobName
       ORDER BY ja.start_execution_date DESC)
END

然後像這樣查詢它:

SELECT [dbo].[fnGetLatestAgentJobExitCode]('myJob')

這將給出以下結果之一:

Failed
Succeeded
Retry
Cancelled
In Progress

或者,如果沒有工作歷史記錄,將不返回任何結果。在您的特定案例中使用它很簡單:

WHILE (SELECT [dbo].[fnGetLatestAgentJobExitCode]('myJob') = 'In Progress')
BEGIN
   WAITFOR DELAY '00:00:05.000'

   IF (SELECT [dbo].[fnGetLatestAgentJobExitCode]('myJob') = 'Failed')
   BEGIN
       BREAK
   END
END

IF (SELECT [dbo].[fnGetLatestAgentJobExitCode]('myJob') = 'Succeeded')
BEGIN
   EXEC msdb.dbo.sp_start_job 'myJob'
END

引用自:https://dba.stackexchange.com/questions/268833