msdb.dbo.sp_start_job got stuck in stored procedure

1.5k views Asked by At

I have a stored procedure USP_A with logic like following:

......
exec dbo.usp_Log 'Start to run job job1'
Exec @intErrorCode = msdb.dbo.sp_start_job 'job1'   
  IF @intErrorCode <> 0 Goto errorHandling
exec dbo.usp_Log 'End to run job job1'
......

But when I run this stored procedure, it got stuck and when I check log I can only see message 'Start to run job job1'. Also in the SQL Server Agent job monitor I can not see this job get triggered.

But if I manually run

Exec @intErrorCode = msdb.dbo.sp_start_job 'job1' 

it works fine.

The SQL Server is Microsoft SQL Server 2005 Enterprise Edition (version 9.00.5000.00)

2

There are 2 answers

0
mhan0125 On BEST ANSWER

It turns out to be some kind of SQL Server bug (Maybe the SQL Server 2005 is quite old). The stored procedure just ended unexpectedly and does not return any code.

So the problem is solved by moving all the logic before this msdb.dbo.sp_start_job procedure into a separate stored procedure.

Hope it can help anyone who got this same issue.

6
Brian Pressler On

Your job is probably failing to start and branching to the errorHandlingsection of your code. If you add @@ERROR_MESSAGE to the log first, then you will see the problem in your log. Something like:

exec dbo.usp_Log 'Start to run job job1'
begin try
    Exec @intErrorCode = msdb.dbo.sp_start_job 'job1'
end try
begin catch
    exec dbo.usp_Log 'Error: ' + ERROR_MESSAGE()
    Goto errorHandling
end catch
exec dbo.usp_Log 'End to run job job1'

UPDATE

I ran a test on my server. I tried to initiate a job that was already running and an error was returned, but did not trigger the catch block. Apparently this is a problem with sp_start_job. This may be the source of some of your confusion. There is a workaround posted here: TRY/CATCH does not work on SQL Server Agent error?

My best guess though is that there is a permission issue when the code is run under a different user context. You could wrap the code to run the job into a procedure that executes under a different security context... like this:

create procedure dbo.sp_RunJob1
with execute as owner
as
exec sp_start_job @job_name = 'job1'

Then call the sp_RunJob1 instead of the sp_start_job statement in your code.