您的位置:首页 > 运维架构

使用Tql执行一个job,并监控job的运行状态

2015-06-03 14:52 856 查看
1,创建一个job 执行的stored procedure

ALTER PROCEDURE [dbo].[usp_add_test1]
AS
BEGIN
SET NOCOUNT ON;
WAITFOR DELAY '00:00:03'

insert into dbo.test(code,name,txt)
select top 1 code+1 code,name,N'job1'
from dbo.test
order by code desc
END


2,创建一个job,执行以下sql代码

exec dbo.usp_add_test1


3,使用 msdb.dbo.sp_start_job 启动job,这个stored procedure 不等job执行完成就退出,返回的结果是启动job的status。

EXEC msdb.dbo.sp_start_job N'test1'


4,使用 msdb.dbo.sp_help_job 查看job执行的status,status is int, with a default of NULL, and can be one of these values.

Value

Description

0

Returns only those jobs that are not idle or suspended.

1

Executing.

2

Waiting for thread.

3

Between retries.

4

Idle.

5

Suspended.

7

Performing completion actions.

msdb.dbo.sp_help_job 会返回 Job,Shcedules,steps 和targets 四种的执行情况,由于我们只需要查看job的运行状态,所以@job_aspect=‘job’

[ @job_aspect =] 'job_aspect'

The job attribute to display. job_aspect is varchar(9), with a default of NULL, and can be one of these values.

Value

Description

ALL

Job aspect information

JOB

Job information

SCHEDULES

Schedule information

STEPS

Job step information

TARGETS

Target information

执行以下语句就会查看到job test1的执行状态,为了便于编程,必须获取结果集中的current_execution_status字段的值。

EXEC msdb.dbo.sp_help_job @job_name =N'test1',@job_aspect = 'JOB'


使用openrowset,执行以上代码获取current_execution_status字段的值,如果current_execution_status字段的值是4,表明job已经运行成功。

--开启 openrowset 功能
exec sp_configure 'show advanced options', 1;
RECONFIGURE;
exec  sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

declare @current_execution_status int
SELECT @current_execution_status=t.current_execution_status
FROM OPENROWSET(
'SQLNCLI',
'Server=.;Trusted_Connection=yes;',
' EXEC msdb.dbo.sp_help_job @job_name =N''test1'',@job_aspect = ''JOB'''
) AS t;


但是,这里有一个issue,

Msg 11520, Level 16, State 1, Procedure sp_describe_first_result_set, Line 1
The metadata could not be determined because statement 'EXECUTE master.dbo.xp_sqlagent_is_starting @retval OUTPUT' in procedure 'sp_is_sqlagent_starting' invokes an extended stored procedure.

微软官方blog给出了一个解决方法,URL如下:
http://blogs.msdn.com/b/sqlagent/archive/2012/07/12/workaround-sql-server-2012-openrowset-on-msdb-dbo-sp-help-job-throws-error.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: