You can use SQL Agent tokens to get the name or ID of the currently executing job (http://technet.microsoft.com/en-us/library/ms175575(v=sql.105).aspx).
To set this up, do the following:
- Add new step "Email job history" to the end of your job
- Change each job step to have an "OnFailure" action of "Go to step: {n} Email job history", where {n} is the step # of the step added above.
- Use the SQL Agent tokens to get your currently executing
JOBID
and any other info you need. Example of "Email job history" T-SQL step below, wheremsdb.dbo.usp_SQLAgentSendJobStepFailedEmail
would be your procedure name:
Example of "Email job history" T-SQL step:
DECLARE @jobid uniqueidentifier, @run_date int, @run_time int, @profile_name sysname;
set @profile_name = 'MyDatabaseMailProfileName';
--USE SQL AGENT "TOKENS" TO GET CURRENT JOB PARAM VALUES
set @jobid = $(ESCAPE_NONE(JOBID));
set @run_date = $(ESCAPE_NONE(STRTDT));
set @run_time = $(ESCAPE_NONE(STRTTM));
EXEC msdb.dbo.usp_SQLAgentSendJobStepFailedEmail @jobid = @jobid, @run_date = @run_date, @run_time = @run_time, @email_profile_name = @profile_name;