DOWNLOAD THE CODE:
Download the Code 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.
—Jameel Ahmed, Database Administrator/ Analyst, Canaccord Capital Corp.

End of Article




You must log on before posting a comment.

If you don't have a username & password, please register now.

Reader Comments

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.

vkomarovsky

Article Rating 5 out of 5

Which version of SQL Server and Service Pack are you using? I will need to regenerate the error to help you out.

jameel_ahmed

Article Rating 3 out of 5

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

rdv92

Article Rating 4 out of 5

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

victorcheng

Article Rating 5 out of 5

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

deannamw

Article Rating 3 out of 5

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.

jameel_ahmed

Article Rating 5 out of 5

I cannot download zip file with code for this article. I get 404 error 'Page not found'.

kHemo

Article Rating 1 out of 5

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?

tarehart1

Article Rating 2 out of 5

Hi tarehart1 & vkomarovsky, I was able to regenerate this on SQL 2005 RTM and i am looking into this issue.

jameel_ahmed

Article Rating 5 out of 5

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:

jameel_ahmed

Article Rating 5 out of 5

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

jameel_ahmed

Article Rating 5 out of 5

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

salnasi

Article Rating 5 out of 5

Never mind my last comment.

I found the fix in your article. $(ESCAPE_NONE(JOBID))

salnasi

Article Rating 5 out of 5

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?

dedbeat

Article Rating 5 out of 5

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

manit77

Article Rating 4 out of 5

See More Comments  1   2 
 
 

ADS BY GOOGLE