SQL Server Agent - get my own job_id

sql server get current job id
query to get list of jobs in sql server
how to check job status in sql server using query
how to find ssis jobs in sql server
sql agent job report
sql server job definition
sql server query job details
who created sql server job

I'm running a SQL Server 2008 64 bit Developer Edition with Service Pack 1 installed. I have a SQL Server Agent Job. Within this job I want to get the job_id of my own job. On MSDN (http://msdn.microsoft.com/en-us/library/ms175575(v=SQL.100).aspx) you can find a description of using tokens in job steps. Wow, great, that's what I'm looking for!! Just use (JOBID). Since SQL Server 2005 SP1 you have to use macro like $(ESCAPE_NONE(JOBID)). No problem. But if you try the example:

DECLARE @name NVARCHAR(128)
select @name =  name from msdb.dbo.sysjobs where job_id = $(ESCAPE_SQUOTE(JOBID))
PRINT @name

you get: Incorrect syntax near 'ESCAPE_SQUOTE'. (Microsoft SQL Server, Error: 102) Ok, now from the scratch:

PRINT N'$(ESCAPE_SQUOTE(JOBID))'  

results in 0xE33FE637C10B3C49A6E958BB3EF06959 but the job_id is 37E63FE3-0BC1-493C-A6E9-58BB3EF06959 The "N'" I think makes an implicit conversion to NVARCHAR of the (JOBID)... Ok, I think I have to care about the datatype of (JOBID). In the book "SQL Server 2008 Administration" on page 168/169 there's also an example of using (JOBID):

declare @jobid binary(16)
SELECT @jobid =Convert(Uniqueidentifier,$(ESCAPE_NONE(JOBID)))

results in: Incorrect syntax near '('. (Microsoft SQL Server, Error: 102) I'm totally confused now. Could please someone help me with a good advice or solution. Every kind of help is appreciated.

Best regards Helmut

Just forget what parser is saying - variable resolution is done at runtime. Parser does not know about that.

Identifying SQL Agent Job Name based on the job id , The "0x" in front of the job_id tells SQL Server to convert it to a hex value which then matches with the sysjobs table. */. select * from  Since SQL Server 2005 SP1 you have to use macro like $(ESCAPE_NONE(JOBID)). No problem. But if you try the example: DECLARE @name NVARCHAR(128) select @name = name from msdb.dbo.sysjobs where job_id = $(ESCAPE_SQUOTE(JOBID)) PRINT @name you get: Incorrect syntax near 'ESCAPE_SQUOTE'. (Microsoft SQL Server, Error: 102) Ok, now from the scratch:

We had trouble with this recently and did not go the route you found in MSDN. Instead, we recovered the jobid from dbo.sysjobs by name directly (the opposite of your example) and then used that within the job to check execution status (exiting out of long running while loop if job state had changed).

declare @jobid uniqueidentifier
SELECT @jobid = job_id from msdb.dbo.sysjobs where name = '[blah]'

Get Job id OR Job name from within executing job, You will have to use tokens in your job steps to get your own job id. I was using the invoke-sqlcmd cmdlet in powershell though the sql agent. You will have to use tokens in your job steps to get your own job id. Details here: Using Tokens in Job Steps. At the end of the article there's one example with jobid: SELECT * FROM msdb.dbo.sysjobs WHERE @JobID = CONVERT(uniqueidentifier, $(ESCAPE_NONE(JOBID))) ;

thanks for your answers. The problem is that I tried to parse the statement in job step. Then I got this error. While running the job there's no problem. My very best solution now is:

declare @JobID uniqueidentifier
SELECT @JobID = $(ESCAPE_NONE(JOBID));
PRINT 'My JobID is  ' + Convert(char(255), @JobID)  

Now you handle with @JobID, but as far as I know until now you have to convert always to char(255). Thanks to user state_dba on MSDN.

Queries to inventory your SQL Server Agent Jobs, The result set for the script displays the jobs in ascending order by creation date. -- list of jobs; selected info about jobs SELECT job_id ,name ,  SQL Server Agent Job Execution Information. SQL Server Agent stores the history of job execution in system tables in msdb database. The following query gives us the details of last/latest execution of the SQL Server Agent Job and also the next time when the job is going to run (if it is scheduled).

This may sound obvious, but I get the error you quoted from your first sample, if I run it in a query window, but it runs perfectly well when I paste that script into a job step.

You can only use these tokens within job steps. And, given that we're not expecting any quotes in the jobid token, I'd use ESCAPE_NONE whenever you reference it.

Query SQL Server Agent Jobs, Job Steps, History and Schedule , In it, one can find the jobs, job steps, schedules, operators, and Each SQL Server Agent Job is stored as a row in the table Each step in a job is found in the table msdb.dbo.sysjobsteps and they are joined using the job_id  Benefits of SQL Server Agent. SQL Server Agent uses SQL Server to store job information. Jobs contain one or more job steps. Each step contains its own task, for example, backing up a database. SQL Server Agent can run a job on a schedule, in response to a specific event, or on demand.

For those that need an alternative method to get your own job ID without macros, for example, from within a stored procedure that a job step calls. I found the following here

DECLARE @SQL NVARCHAR(72),
@jobID UNIQUEIDENTIFIER,
@jobName SYSNAME

IF SUBSTRING(APP_NAME(),1,8) = 'SQLAgent'
BEGIN 
    SET @SQL = 'SET @guid = CAST(' + SUBSTRING(APP_NAME(), 30, 34) + ' AS UNIQUEIDENTIFIER)'

    EXEC    sp_executesql @SQL, N'@guid UNIQUEIDENTIFIER OUT', @guid = @jobID OUT

    SELECT  @jobName = name
    FROM    msdb..sysjobs
    WHERE   job_id = @jobID
END

How to get SQL Server Agent job history - Solution center, who owns the SQL Server that contains hundred of SQL Agent Jobs? The SQL Server Agent jobs information stored in the MSDB database includes In order to get the execution history about a specific SQL Server Agent job, [​sysjobs] J ON JH.job_id= J.job_id WHERE J.name='Log_Failed_Logins'. By digging into the code samples in this tip, you can develop rich SQL Server Agent Job schedule applications as well as get started creating your own custom code library for creating schedules, attaching schedules, and detaching schedules.

sp_start_job (Transact-SQL), Instructs SQL Server Agent to execute a job immediately. [ @job_id = ] job_id The identification number of the job to start. Members of SQLAgentUserRole and SQLAgentReaderRole can only start jobs that they own. Similar to SQL Server Agent job dependency. However, I'm looking to make it intelligent enough that if Job 1 isn't finished yet by the scheduled time Job 2 will try to run again at a later interval. However, I'm looking to make it intelligent enough that if Job 1 isn't finished yet by the scheduled time Job 2 will try to run again at a later

sp_help_jobhistory (Transact-SQL), Provides information about the jobs for servers in the multiserver [ @job_id = ] job_id The job identification number. job_id is returned by Microsoft SQL Server when executing the job. sql_message_id is int, with a default of NULL. Other users must be granted one of the following SQL Server Agent  SQL Server: Script to find all Running SQL Server Agent JOB; SQL Server: Script to get the SSIS Packages of MSDB; SQL Server: The truth about TABLE WITH (NOLOCK) SQL Server: Database Log Shipping Interview Questions and Answers (Day-1) SQL Server: Important System Tables for Alerts, SQL Jobs, Operators

Detecting and Alerting on SQL Server Agent Missed Jobs, To find instances of missed SQL Server Agent jobs, we need to read the job history in MSDB and compare the Our first task is to collect the job run history for a given server. ON sysjobs.job_id = sysjobhistory.job_id Tailor your own processes to fit the data and make best use of your existing tools. Browse other questions tagged sql-server sql-server-agent jobs or ask your own question. The Overflow Blog The Overflow #26: The next right thing