views:

251

answers:

2

I don't suppose anyone knows whether a SQL Server Agent Job can ask information about itself, such as its own ID, or the path it's running from? I'm aware of xp_sqlagent_enum_jobs and sp_help_job but this doesn't help, because you have to specify the job ID.

The idea is that we want code that we don't have to manage by being able to call a sproc which will identify the current job. Any ideas?

+1  A: 

Yes, but it isn't pretty.

Look at the sys.sysprocesses (or dbo.sysprocesses in SQL 2000 and below). The program name will be SQL Agent something with a binary value at the end. That binary value is the binary vale of the guid of the job. So, substring out that value and do a lookup against the msdb.dbo.sysjobs table to find out what job it is (you'll need to cast the sysjobs.job_id to varbinary(100) to get the values to match).

I told you it wasn't pretty, but it will work.

mrdenny
Well it's useful to know. I will follow this up, I ran a quick query and it was quite easy to show. I'm still not able to see how the SQL Server Agent would be able to query a job about _itself_ though. The scheduler would kick off and a job would be running, but how could it ask itself?
Kezzer
There's no way per say to find out about it self, as there's no function which will tell you what jobid you are running. As I referred to above you can take the current spid that the job is running under, use that to find the binary value of the application name, then use that to find the correct jobid from the sysjobs table. This would then allow you to query the job history tables to find out information about the current job. You could even write a function to handle the string work and return the jobid like a system function would if it existed.
mrdenny
A: 

nasty!!! but i think it might work...

eg. used within a job - select * from msdb..sysjobs where job_id = dbo.fn_currentJobId()

let me know.

create function dbo.fn_CurrentJobId()
returns uniqueidentifier
as
begin
declare @jobId uniqueidentifier

select @jobId = j.job_id
from master..sysprocesses s (nolock)
join msdb..sysjobs j (nolock)
on (j.job_id = SUBSTRING(s.program_name,38,2) + SUBSTRING(s.program_name,36,2) + SUBSTRING(s.program_name,34,2) + SUBSTRING(s.program_name,32,2) + '-' + SUBSTRING(s.program_name,42,2) + SUBSTRING(s.program_name,40,2) + '-' + SUBSTRING(s.program_name,46,2) + SUBSTRING(s.program_name,44,2) + '-' + SUBSTRING(s.program_name,48,4) + '-' + SUBSTRING(s.program_name,52,12) ) where s.spid = @@spid

return @jobId
end
go

thanks for the info though

hardus

related questions