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

Executing SQL Server Agent Job from a stored procedure and returning job result(从存储过程执行 SQL Server 代理作业并返回作业结果)
本文介绍了从存储过程执行 SQL Server 代理作业并返回作业结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

需要有一个存储过程来调用 SQL Server 代理作业并返回该作业是否成功运行.

Need to have a stored procedure that calls a SQL Server Agent Job and returns whether or not the job ran successfully or not.

到目前为止我有

So far I have

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

哪个开始工作,如果工作成功与否,返回的最佳方法是什么?

Which starts the job, whats the best way to get back if the job ran successfully or not?

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

Ok made an edit and used WAITFOR DELAY as the job normally runs between 3-4 mins never longer than 4. Does the job but is there a more efficient way to do it?

推荐答案

您可以运行查询:

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

它将返回一列 run_status.状态为:

It'll return a column run_status. Statuses are:

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

有关 MSDN

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

EDIT: You might want to to poll your job and make sure it's executed. You can get this information from sp_help_job procedure. When this procedure returns status of 4 it means the job is idle. Then it's safe to check for it's run status.

您可以使用以下代码进行投票:

You can poll using following code:

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,我们就知道工作已完成,可以安全地检查工作历史记录.

This code will check for the status, wait for 3 seconds and try again. Once we get status of 4 we know the job is done and it's safe to check for the job history.

这篇关于从存储过程执行 SQL Server 代理作业并返回作业结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)