从存储过程执行SQL Server代理作业并返回作业结果

时间:2012-09-03 13:42:10

标签: sql sql-server sql-server-2008 tsql jobs

需要一个调用SQL Server代理作业的存储过程,并返回作业是否成功运行。

到目前为止,我有

CREATE PROCEDURE MonthlyData
AS
EXEC msdb.dbo.sp_start_job N'MonthlyData'

WAITFOR DELAY '000:04:00'

EXEC msdb.dbo.sp_help_jobhistory @job_name = 'MonthlyData'
GO

哪个开始这项工作,如果工作顺利成功,最好的办法是什么?

确定编辑并使用了WAITFOR DELAY,因为作业通常在3-4分钟之间运行,从不超过4分。是否有更有效的方法来完成工作?

5 个答案:

答案 0 :(得分:20)

对于不允许使用 OPENROWSET 命令的所有人,这可能有所帮助。我在这里找到了解决方案的开始:

http://social.msdn.microsoft.com/Forums/en-US/89659729-fea8-4df0-8057-79e0a437b658/dynamically-checking-job-status-with-tsql

这依赖于以下事实: msdb.dbo.sysjobactivity 表的某些列首先在作业以某种方式完成后填充。

-- Start job
DECLARE @job_name NVARCHAR(MAX) = 'JobName'
EXEC msdb.dbo.sp_start_job @job_name = @job_name


-- Wait for job to finish
DECLARE @job_history_id AS INT = NULL

WHILE @time_constraint = @ok
BEGIN
    SELECT TOP 1 @job_history_id = activity.job_history_id
    FROM msdb.dbo.sysjobs jobs
    INNER JOIN msdb.dbo.sysjobactivity activity ON activity.job_id = jobs.job_id
    WHERE jobs.name = @job_name
    ORDER BY activity.start_execution_date DESC

    IF @job_history_id IS NULL
    BEGIN
        WAITFOR DELAY '00:00:10'
        CONTINUE
    END
    ELSE
        BREAK
END


-- Check exit code
SELECT history.run_status
FROM msdb.dbo.sysjobhistory history
WHERE history.instance_id = @job_history_id

您可能希望对WHILE-loop允许运行的时间进行一些检查。我选择将这一部分排除在榜样之外。

Microsoft退出代码指南等: http://technet.microsoft.com/en-us/library/ms174997.aspx

答案 1 :(得分:19)

您可以运行查询:

EXEC msdb.dbo.sp_help_jobhistory 
    @job_name = N'MonthlyData'

它将返回一列run_status。状态是:

 0 - Failed
 1 - Succeeded
 2 - Retry
 3 - Canceled         

有关MSDN

的更多信息

编辑:您可能想要轮询您的工作并确保其已执行。您可以从sp_help_job过程获取此信息。当此过程返回4状态时,表示作业处于空闲状态。 然后检查它的运行状态是安全的。

您可以使用以下代码进行轮询:

DECLARE @job_status INT
SELECT @job_status = current_execution_status FROM OPENROWSET('SQLNCLI', 'Server=.;Trusted_Connection=yes;','exec msdb.dbo.sp_help_job @job_name = ''NightlyBackups''')

WHILE @job_status <> 4
BEGIN
    WAITFOR DELAY '00:00:03'
    SELECT @job_status = current_execution_status FROM OPENROWSET('SQLNCLI', 'Server=.;Trusted_Connection=yes;','exec msdb.dbo.sp_help_job @job_name = ''NightlyBackups''')
END

EXEC msdb.dbo.sp_help_jobhistory 
    @job_name = N'NightlyBackups' ;
GO

此代码将检查状态,等待3秒后再试一次。一旦我们获得4的状态,我们就知道工作已经完成,并且检查工作历史是安全的。

答案 2 :(得分:0)

我可能会有点迟,但我发现以下查询对我有用。它将给出执行时间和执行结束时间。你可以改变它以获得状态。

SELECT 
    job.name, 
    job.job_id, 
    job.originating_server, 
    activity.run_requested_date, 
    activity.stop_execution_date, 
    DATEDIFF( SECOND, activity.run_requested_date, activity.stop_execution_date ) as Elapsed 
FROM msdb.dbo.sysjobs_view job 
JOIN msdb.dbo.sysjobactivity activity ON job.job_id = activity.job_id 
JOIN msdb.dbo.syssessions sess ON sess.session_id = activity.session_id 
JOIN 
( 
    SELECT 
    MAX( agent_start_date ) AS max_agent_start_date 
    FROM 
    msdb.dbo.syssessions 
) sess_max 
ON sess.agent_start_date = sess_max.max_agent_start_date 
WHERE run_requested_date IS NOT NULL 
--AND stop_execution_date IS NULL 
AND job.name = @JobName

答案 3 :(得分: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, -- BOOL
request_source        INT              NOT NULL,
request_source_id     sysname          COLLATE database_default NULL,
running               INT              NOT NULL, -- BOOL
current_step          INT              NOT NULL,
current_retry_attempt INT              NOT NULL,
job_state             INT              NOT NULL)

DECLARE @job_id uniqueidentifier ;
select @job_id = job_id from msdb.dbo.sysjobs where name = 'Job1';
insert into @xp_results
EXEC master.dbo.xp_sqlagent_enum_jobs 1, sa, @job_id

select case when running = 1 then 'Currently Running' else '' end as running, 
case job_state 
    when 0 then 'Not Idle or Suspended'
    when 1 then 'Executing Job'
    when 2 then 'Waiting For Thread'
    when 3 then 'Between Retries'
    when 4 then 'Idle'
    when 5 then 'Suspended'
    when 6 then 'WaitingForStepToFinish'
    when 7 then 'PerformingCompletionActions'
end as job_state
from @xp_results

IF (select running from @xp_results) <> 1
    EXEC msdb.dbo.sp_start_job 'Job1'

答案 4 :(得分:0)

@lapponiandevil 在这里有最好、最有用的解决方案,但他们的代码比它需要的稍微复杂一点,实际上并不能按原样工作,因为它需要 @Time_constraint 和 @ok 变量,这些变量在显示代码。

这些是为了支持代理作业的超时,但这不是必需的。代理作业步骤可以配置有自己的超时值,如果超过它就会正确地出错,这与他们的代码不同。如果您使用该超时方法,您可能会发现自己正在寻找幻象错误,或者在您进入流程的下一步时不知道您正在等待的代理作业仍在运行。

我认为将代码减少到最低限度并删除超时功能是理想的。这是我根据他们的解决方案得出的结论:

-- Start Agent Job
DECLARE @JobName NVARCHAR(128) = 'My Agent Job Name'
   EXEC msdb.dbo.sp_start_job @JobName

-- Wait for Agent Job to finish
DECLARE @HistoryID AS INT = NULL
  WHILE @HistoryID IS NULL
  BEGIN
        --Read most recent Job History ID for the specified Agent Job name
            SELECT TOP 1 @HistoryID = b.job_history_id
              FROM msdb.dbo.sysjobs a
        INNER JOIN msdb.dbo.sysjobactivity b ON b.job_id = a.job_id
             WHERE a.name = @JobName
          ORDER BY b.Start_execution_date DESC
        --If Job is still running (Job History ID = NULL), wait 3 seconds
                IF @HistoryID IS NULL WAITFOR DELAY '00:00:03'
    END

-- Check Agent Job exit code to make sure it succeeded
     IF (SELECT run_status 
           FROM msdb.dbo.sysjobhistory 
          WHERE instance_id = @HistoryID) <> 1 
  THROW 69000, 'Child Agent Job failure', 1;