我sp_start_job
用来开始工作。
作业 ( test2
) 只有一步:
select getdate()
waitfor delay '00:00:10'
TRY/CATCH
代码:
begin try
EXEC msdb.dbo.sp_start_job @job_name = 'test2'
end try
begin catch
print 'error'
end catch
第一次运行代码:
作业“test2”成功启动。
代码的第二次运行(10 秒内):
消息 22022,级别 16,状态 1,第 0 行
SQLServerAgent 错误:运行作业 test2 的请求(来自用户 sa)被拒绝,因为作业已经从用户 sa 的请求中运行。
为什么TRY/CATCH
在这种情况下不起作用?
更新:我首先应该补充一点,我正在使用具有链接服务器(sql server 2000)的 sql server 2005。我试图在 sql server 2005 服务器上编写一个 proc,以查看所有链接服务器上的作业。如果作业未运行,请运行它。最初,我使用 try - catch 并希望在运行已经运行的作业但失败(此线程)时捕获任何错误。
我终于使用了以下代码:(它不会编译,你需要替换一些变量,只是给出一个想法)
CREATE TABLE [dbo].[#jobInfo](
[job_id] [uniqueidentifier] NULL,
[originating_server] [nvarchar](30) ,
[name] [nvarchar](128) ,
[enabled] [tinyint] NULL,
[description] [nvarchar](512) ,
[start_step_id] [int] NULL,
[category] [nvarchar](128) ,
[owner] [nvarchar](128) ,
[notify_level_eventlog] [int] NULL,
[notify_level_email] [int] NULL,
[notify_level_netsend] [int] NULL,
[notify_level_page] [int] NULL,
[notify_email_operator] [nvarchar](128) ,
[notify_netsend_operator] [nvarchar](128) ,
[notify_page_operator] [nvarchar](128) ,
[delete_level] [int] NULL,
[date_created] [datetime] NULL,
[date_modified] [datetime] NULL,
[version_number] [int] NULL,
[last_run_date] [int] NOT NULL,
[last_run_time] [int] NOT NULL,
[last_run_outcome] [int] NOT NULL,
[next_run_date] [int] NOT NULL,
[next_run_time] [int] NOT NULL,
[next_run_schedule_id] [int] NOT NULL,
[current_execution_status] [int] NOT NULL,
[current_execution_step] [nvarchar](128) ,
[current_retry_attempt] [int] NOT NULL,
[has_step] [int] NULL,
[has_schedule] [int] NULL,
[has_target] [int] NULL,
[type] [int] NOT NULL
)
SET @sql =
'INSERT INTO #jobInfo
SELECT * FROM OPENQUERY( [' + @srvName + '],''set fmtonly off exec msdb.dbo.sp_help_job'')'
EXEC(@sql)
IF EXISTS (select * from #jobInfo WHERE [name] = @jobName AND current_execution_status IN (4,5)) -- 4: idle, 5: suspended
BEGIN
SET @sql = 'EXEC [' + @srvName + '].msdb.dbo.sp_start_job @job_name = ''' + @jobName + ''''
--print @sql
EXEC (@sql)
INSERT INTO #result (srvName ,status ) VALUES (@srvName, 'Job started.')
END ELSE BEGIN
INSERT INTO #result (srvName ,status ) VALUES (@srvName, 'Job is running already. No action taken.')
END