Have SQL Server Email You Error Messages Generated by Job Failures

Downloads
96056.zip

When a SQL Server job fails, you can have SQL Server Agent send you a notification. However, as Figure 1 shows, the notification doesn't include the error message generated by that job failure. So, you have to connect to SQL Server to read the error message to determine whether the failure is being caused by a critical problem.

Because it's helpful to receive the error messages generated by failed jobs, I created a SQL Server job step that calls a stored procedure named spDBA_job_notification. The job step passes the failed job's ID to the stored procedure. The stored procedure uses the job ID to query the msdb agent tables for the most recent error message for that job. The stored procedure incorporates the error message into an email and sends the email to the specified person. Figure 2 shows an example of an email sent by the stored procedure.

To pass the job ID to the stored procedure from within the job, I use a SQL Server Agent token. SQL Server Agent lets you use tokens in T-SQL job step scripts. In SQL Server, various tokens represent job elements. For example, the SRVR token represents the server running SQL Server, the A-DBN token represents the name of the database running the job, and the JOBID token represents the job ID. (For a complete list of tokens, see the "Using Tokens in Job Steps" section in SQL Server 2005 Books Online—BOL, which you can access at http://msdn2.microsoft.com/en-us/library/ms175575.aspx.) When you insert a token in a job step script, SQL Server Agent replaces the token with the element it represents at run time.

You set up job steps in SQL Server Management Studio (SSMS). Open SSMS, expand SQL Server Agent (it must be running), then expand Jobs. Right-click the target job and select Properties. In the Job Properties dialog box, select Steps from the Select a page menu on the left. Figure 3 shows an example of the Job step list section that appears.

In Figure 3, note that there are two steps. In step 1, the job is run. In this case, the job is a T-SQL script named Simple select. (You can download SQLJob_Create.sql, which will create this test job, from the SQL Server Magazine Web site.) When the Simple select script runs without any problems, a completion status of success is logged. When the Simple select script encounters a problem that causes it to fail, step 2 executes.

Figure 4 shows an example of the settings for step 2. Because the spDBA_job_notification stored procedure resides in the master database, the Database dropdown list is set to master. If you're running SQL Server 2005 SP1 or later, the command for step 2 is

EXEC spDBA_job_notification
  $(ESCAPE_NONE(JOBID))

If you're running a version earlier than SQL Server 2005 SP1, the command is

EXEC spDBA_job_ notification \[JOBID\]

This command calls the spDBA_job_notification stored procedure. The SQL Server Agent engine replaces the $(ESCAPE_NONE (JOBID)) or \[JOBID\] token with the job ID before executing the stored procedure. You can download spDBA_ job_notification.sql from the SQL Server Magazine Web site. To use this script, you need to have Database Mail set up. If it isn't set up, you can do so with DBMail_Setup.sql, which you can also download from the SQL Server Magazine Web site.

If you were to manually supply the job ID and execute spDBA_job_notification, the stored procedure wouldn't work. The stored procedure must be called from within a job step because it checks for the most recent job history without a completion status. When you run it in SSMS, the job is already completed and has a status of either success or failure.

If someone were to make changes to the stored procedure that would cause it to fail or if someone were to comment out the email section in the code, you wouldn't receive any notifications. For this reason, I highly recommend you also set up the job's Notifications page as a backup measure so that you get notified of job failures. You can access the Notifications page from the Job Properties dialog box.

Discuss this Article 24

manit (not verified)
on Apr 30, 2008
fixed syntax error: -- Build the Email Body set @Body = @Body + 'Step name= ' + @step_name + @CrLf + 'DB Name = ' + convert(varchar(50), ISNULL(@DBname,')) + @CrLf + 'Run Date = ' + convert(varchar(50),@run_datetime ) + @CrLf
vitaly (not verified)
on Jul 2, 2007
I tried it for "before SP1" SQL Server 2005 using the command exec spDBA_job_notification [JOBID] and it failed with an error Error converting data type nvarchar to uniqueidentifier. [SQLSTATE 42000] (Error 8114). The step failed. Looks like something breaks when JOBID parameter is being passed to SP.
Deanna (not verified)
on Jul 6, 2007
I am trying to use these scripts and they are not working. Should they work in this version of SQL Server? Microsoft SQL Server 2000 - 8.00.2040 (Intel X86) Enterprise Edition on Windows NT 5.2 (Build 3790: Service Pack 1) SP4 Enterprise Edition Thanks, Deanna
jameel_ahmed
on Nov 18, 2011
The procedure uses the msdb system tables to query the detailed error message. So you need to ensure that you are logging the job step output to the log table, in order to receive the emails.
dedbeat
on Mar 7, 2008
hey i think this is a superb idea. unfortunately when creating the SP i get an error. Msg 156, Level 15, State 1, Procedure spDBA_job_notification, Line 68 Incorrect syntax near the keyword 'if'. any thoughts?
jameel_ahmed
on Aug 7, 2012
It does works with jobs containing multiple steps. You need to ensure that "On Failure" does jump to the failure detailed step. Let me know if you still have problems.
KBemowski
on Jul 23, 2009
I checked with Jameel and you're correct. He sent along a corrected version of spDBA_job_notification.sql, which is now in the 96056.zip file. Thanks for letting us know about this! Karen Bemowski, senior editor, SQL Server Magazine, Windows IT Pro
SIDNEY (not verified)
on Oct 11, 2007
Never mind my last comment. I found the fix in your article. $(ESCAPE_NONE(JOBID))
SIDNEY (not verified)
on Oct 11, 2007
I am using SQL 2005 SP2 and this is the error I am getting-- The job step contains tokens. For SQL Server 2005 Service Pack 1 or later, you must use the appropriate ESCAPE_xxx macro to update job steps containing tokens before the job can run. Thanks in advance
jameel_ahmed
on Jul 3, 2007
Which version of SQL Server and Service Pack are you using? I will need to regenerate the error to help you out.
jameel_ahmed
on Jul 12, 2007
Hi tarehart1 & vkomarovsky, I was able to regenerate this on SQL 2005 RTM and i am looking into this issue.
jameel_ahmed
on Jul 9, 2007
Hi Deanna, SQLJob_Create.sql works on both SQL 2000 + SQL2005. But on SQL 2000, you need to modify the fail Job step to use: EXEC spDBA_job_notification [JOBID] instead of EXEC spDBA_job_notification $(ESCAPE_NONE(JOBID)) DBMail_Setup_sql is for SQL 2005 only. for SQL 2000 you will need to setup SQL Mail, refer to Books Online. spDBA_job_notification.sql This can be created on SQL 2000. but you will need to change the send email call from msdb.dbo.sp_send_dbmail (SQL 2005 specific) to use SQL 2000 SQL Mail procedure msdb..xp_sendmail I have successfully tested spDBA_job_notification procedure on SQL 2000 SP4: Microsoft SQL Server 2000 - 8.00.2039 (Intel X86) Standard Edition on Windows NT 5.2 (Build 3790: ) Can you tell the exact error message you are getting. Thank you, Jameel.
kHemo (not verified)
on Jul 11, 2007
I cannot download zip file with code for this article. I get 404 error 'Page not found'.
M (not verified)
on Jul 28, 2008
hi jameel i still have error "Error converting data type nvarchar to uniqueidentifier. [SQLSTATE 42000] (Error 8114). The step failed" what can i do ?? iam using: Microsoft SQL Server 2005 - 9.00.3042.00 (Intel X86) Feb 9 2007 22:47:07 Copyright (c) 1988-2005 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
VICTOR (not verified)
on Jul 5, 2007
Hi; This is very good article, I just want to mention, the uploaded code, the spDBA_job_Notification is giving one syntax error when you run, It might be useful for others. set @Body = @Body + 'Step name= ' + @step_name + @CrLf + 'DB Name = ' + convert(varchar(50), ISNULL(@DBname,')) + @CrLf + 'Run Date = ' + convert(varchar(50),@run_datetime ) + @CrLf One close braket was missing in ISNULL function. Thanks
jameel_ahmed
on Jul 13, 2007
Hi tarehart1 & vkomarovsky & All, Here is the Solution to: Error converting data type nvarchar to uniqueidentifier on SQL2005 RTM (9.0.1399). It seems, eventhough [JOBID] token is documented in Books Online as being supported in SQL2005 RTM, it is not. JOB Tokens seem to only work on SQL 2005 SP1, SP2. I only tested one token, namely JOBID. So RTM users will need to upgrade to SQL2005SP1, or SQL2005SP2. I created a simple stored procedure to test this case, and a simple job with a job step that calls: on SQL2005 RTM : EXEC tempdb..sptoken_test [JOBID] on SQL2005 SP1/SP2: EXEC tempdb..sptoken_test $(ESCAPE_NONE(JOBID)) after the job ran, I queried tempdb..tmpAgentToken for the values that is being passed from agent to TSQL. TSQL script to follow in next post:
tarehart1 (not verified)
on Jul 12, 2007
When running the 'EXEC spDBA_job_notification [JOBID]' step, I am getting the error message of 'Error converting data type nvarchar to uniqueidentifier. [SQLSTATE 42000] (Error 8114). The step failed.' on our SQL Server 9.0.1399 instance. Any suggestions as to what may be causing this error message to be generated?
DAVIDNGUYEN
on Jul 22, 2009
This is a very useful article. I also like to mention there's syntax error when compiling stored procedure spDBA_job_notification.sql: Msg 156, Level 15, State 1, Procedure spDBA_job_notification, Line 68 Incorrect syntax near the keyword 'if'. Thanks. David.
Richard Tylor
on Jun 3, 2010
I do not get any mail from this job.

W2003X64
SQL2008X64 SP1

EXEC spDBA_job_notification 0xF7DA961B4BBB6845950E31CBE3C4DDB9
That is what I found in trace..

any idea?

Arathishetty
on Feb 23, 2012
Thanks for the SP. It works great. But I don't think this works if there are multiple step_id created within a single job_id internally and you are looking for the 3rd message in the list of 4 messages. For example: All the messages are under the same step_id=1. I am mainly interested in the 3rd message which is " *** Error: The copy destination directory 'd:\xxx\xxx' does not exist.". But when it emails me, it only gives me the last one which in this case is "Executed as user: CRTNT\crt-sql-01. The step failed." 37539598 F24AFBD0-87F8-4871-9681-08626E8B635A 1 Log shipping copy job step. 0 0 Microsoft (R) SQL Server Log Shipping Agent ----- START OF TRANSACTION LOG COPY ----- 37539599 F24AFBD0-87F8-4871-9681-08626E8B635A 1 Log shipping copy job step. 0 0 2012-02-23 15:30:03.73 Starting transaction log copy. Secondary ID: 2012-02-23 15:30:03.74 Retrieving copy settings. Secondary ID: '92833699-d6cb-47e8-ac6f-f11bbdab24f6' 2012-02-23 15:30:03.74 Retrieved copy settings. 37539600 F24AFBD0-87F8-4871-9681-08626E8B635A 1 Log shipping copy job step. 0 0 2012-02-23 15:30:03.76 *** Error: The copy destination directory 'd:\xxx\xxx' does not exist.(Microsoft.SqlServer.Management.LogShipping) *** 37539601 F24AFBD0-87F8-4871-9681-08626E8B635A 1 Log shipping copy job step. 0 0 2012-02-23 15:30:03.94 ----- END OF TRANSACTION LOG COPY ----- Exit Status: 1 (Error) 37539602 F24AFBD0-87F8-4871-9681-08626E8B635A 1 Log shipping copy job step. 0 0 Executed as user: CRTNT\crt-sql-01. The step failed. Any ideas? Thanks for your help
Robert (not verified)
on Jul 5, 2007
In the spDBA_job_notifications.sql script I'm getting the following error: Msg 156, Level 15, State 1, Procedure spDBA_job_notification, Line 68 Incorrect syntax near the keyword 'if'. Here's the lines: if (@Err_severity<>0) set @Body = @Body + 'Severity = ' + convert(varchar(10),@Err_severity) + @CrLf
manit (not verified)
on Apr 30, 2008
SQL Version: Microsoft SQL Server 2005 - 9.00.1406.00 (Intel X86) Mar 3 2007 18:40:02 Copyright (c) 1988-2005 Microsoft Corporation Standard Edition on Windows NT 5.2 (Build 3790: Service Pack 2) I get this error message: Unable to start execution of step 2 (reason: line(1): Syntax error). The step failed. I have "Replace tokens for all job responses to alerts" checked and restarted agent. tried with it on and off. Still no luck :(
Richard Tylor
on Jun 3, 2010
I do not get any mail from this job.

W2003X64
SQL2008X64 SP1

EXEC spDBA_job_notification 0xF7DA961B4BBB6845950E31CBE3C4DDB9
That is what I found in trace..

any idea?

jameel_ahmed
on Jul 13, 2007
USE [tempdb] GO IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sptoken_test]') AND type in (N'P', N'PC')) DROP PROCEDURE [dbo].[sptoken_test] GO create PROCEDURE [dbo].[sptoken_test] @job_id varchar(200) as /***************************************************************************************************** Note: I have am using a varchar column instead of uniqueidentifier, only for testing purpose. In RTM, tmpAgentToken.value='JOBID' In SQL2005 SP1, tmpAgentToken.value= varchar representation of a uniqueidentifier value, this will be in an unreadable format. you will need to change the sproc parameter, and the tables datatype to uniqueidentifier to be able to read the value. In SQL2005 SP2, tmpAgentToken.value= varchar representation of a uniqueidentifier value, this will be in an unreadable format. This is how I found that Agent Job token does not work in SQL 2005 RTM release. I haven't tried all Agent token on RTM, I only tried the JOBID token. *****************************************************************************************************/ IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tmpAgentToken]') AND type in (N'U')) drop table tmpAgentToken CREATE TABLE tmpAgentToken (value varchar(200) null,create_date datetime default getdate() not null) insert into tmpAgentToken (value) values ( @job_id ) GO

Please or Register to post comments.

IT/Dev Connections

Las Vegas
September 30th - October 4th

Paul ThurottOur Experts will show you:
• Common SQL Server
Problems
• Best Practices for T-SQL
• SQL Server Integration
Services
• Database Development

Come See Michael Otey & Tim Ford in Person!

Early Registration Now Open

From the Blogs
May 21, 2013
blog

A Common Misconception about MAXDOP

Out of the box, SQL Server is (and has been) able to take advantage of multiple processors/cores without any effort on behalf of administrators....More
May 9, 2013
blog

My ISO 8601-Compliant Signature 2

My family recently just "officially" announced that we're in the process of adopting a child from South Africa. We're quite excited, of course, but there's a ton of paperwork to do—along with the need for gobs of signatures....More
May 8, 2013
blog

Use SSIS for ETL from Hadoop

In this blog post, Mark Kromer walks you through using SSIS as a way to use ETL techniques using Microsoft's Hadoop on Windows (HDInsight) as a source using Hive connectors...More
SQL Server Pro Forums

Get answers to questions, share tips, and engage with the SQL Server community in our Forums.