Discussion:
Can a SQL Server Agent Job know its own Instance Id
(too old to reply)
Tony O
2012-09-13 10:56:26 UTC
Permalink
Is there any way to write a piece of tsql running within an sql server agent
job to get that running job's instance_id (instance_id from sysjobhistory)
and say, write that instance id to a custom log table?
Erland Sommarskog
2012-09-13 21:15:11 UTC
Permalink
Post by Tony O
Is there any way to write a piece of tsql running within an sql server
agent job to get that running job's instance_id (instance_id from
sysjobhistory) and say, write that instance id to a custom log table?
app_name() contains an id, although you will need to do some parsing to
extract it.
--
Erland Sommarskog, SQL Server MVP, ***@sommarskog.se

Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
Tony O
2012-09-14 11:16:29 UTC
Permalink
Unfortunately this gives us only the Job Id and the Step Id. Is there any
way to get the Instance Id?
Post by Tony O
Is there any way to write a piece of tsql running within an sql server
agent job to get that running job's instance_id (instance_id from
sysjobhistory) and say, write that instance id to a custom log table?
app_name() contains an id, although you will need to do some parsing to
extract it.
--
Erland Sommarskog, SQL Server MVP, ***@sommarskog.se

Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
Erland Sommarskog
2012-09-15 17:10:00 UTC
Permalink
Post by Tony O
Unfortunately this gives us only the Job Id and the Step Id. Is there any
way to get the Instance Id?
That's what I get for not actually looking at the table defintion to
see what you are looking for.

Then gain, if you have job_id and step_id and you know that run_status is =
4, you could use sys.dm_exec_connections.connect_time to map to run_date and
run_time in sysjobshistory. At least as long as not two instance of the job
are not starting at the same time. You probably need some leeway when you do
this mapping since the table only has precision by whole seconds. And beware
that the format for date and time is funky...
--
Erland Sommarskog, SQL Server MVP, ***@sommarskog.se

Links for SQL Server Books Online:
SQL 2008: http://msdn.microsoft.com/en-us/sqlserver/cc514207.aspx
SQL 2005: http://msdn.microsoft.com/en-us/sqlserver/bb895970.aspx
rpresser
2012-09-16 03:47:11 UTC
Permalink
Even sysjobhistory.instance_id may not be what you want. See this thread, which claims it identifies the job step, not the job:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=114687&whichpage=1
Continue reading on narkive:
Loading...