Agent 第二篇:用TSQL来启动和查询Job

 Agent Job可以通过TSQL 脚本来管理,管理Agent Job的SP过程位于msdb数据库的dbo 架构下,常用的功能是启动一个job。

一,启动一个Job

用户创建一个Job之后,可以使用TSQL脚本来启动一个job,返回0表示成功开始Job,返回1表示启动Job失败。

msdb.dbo.sp_start_job {[@job_name =] 'job_name'   | [@job_id =] job_id }  
     [ , [@error_flag =] error_flag]  
     [ , [@server_name =] 'server_name']  
     [ , [@step_name =] 'step_name']  
     [ , [@output_flag =] output_flag]

 通过job name来启动一个job:

exec msdb.dbo.sp_start_job N'Weekly Sales Data Backup' ;

二,轮询查询一个Job的状态

由于用户无法查询一个正在执行的job step,因此,当需要查询master step时,尽量创建一个轻量的start step(step_id=1),把master step放在在第二个step上,这样,就可以通过start step来预判master step 是否处于 running的状态。 下面把Loop的主题粘贴出来,仅供参考:

print 'get step history'
--get step history 
select @InstanceId=max(js.instance_id)
from msdb.dbo.sysjobhistory js with(nolock)
where js.job_id=@job_id
    and js.step_id between 1 and 2 -- start step and master step
            
set @StepStatus=null

select @StepStatus=h.run_status
from msdb.dbo.sysjobhistory h with(nolock)
where h.job_id=@job_id
    and h.step_id=2    --master step
    and h.instance_id>=@InstanceId

if @StepStatus is null -- step is running
    or @StepStatus =2    --step is retrying
    or @StepStatus =4    --step is running
begin    
    print 'step is running or retrying'
    set @Loop=@Loop+1
    waitfor delay '15:00'
    continue -- continue loop
end
else -- step has completed
begin
    print 'step has completed'                    
    select @StepStatus as RunStatusID,
        case @StepStatus
            when 0 then 'Failed'
            when 1 then 'Succeeded'
            when 3 then 'Canceled'
        end as RunStatus
    break    --break loop
end

 

 

参考文档:

SQL Server Agent Store Procedure

posted @ 2015-06-30 16:56  悦光阴  阅读(765)  评论(0编辑  收藏  举报