Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Data Management

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Your profile

Authors

Search

XML Feeds

Google Ads

« ReportViewer and the RSPrintClient Control ProblemsSQL Server 2008 Upgrade Technical Reference Guide Available For Download »
comments
Rate Post:
submit to reddit Digg!FacebookDotnetkicks

This falls under DBA scripting and automation. I am going to try to key on these things in the next few weeks after reading Dan's blog titled, "Scripting DBA Actions" here http://blogs.msdn.com/dtjones/archive/2008/11/23/scripting-dba-actions.aspx

If you have a landscape that is of some size then on most of your instances you're going to find yourself mixed into dozens of SQL Agents Jobs that can become a daily task to ensure they ran correctly. Again this is on the basis you have no monitoring tools that will already notify you of problems and failures. Now we all know there is the Notifications option on all jobs. This is great for basic failures, successful runs and completions but if you've ever had to write a job that really did something other than a backup task you're going to find the need for more options in notifying you when certain things fail and or complete. This is also helpful when you don't want large SQL Tasks to stop an entire job but in the same event let you know one update may have not been successful.

So let's say we have a job that first downloads from an internet location, backs up a table, bulk imports the new data from the download, exports to excel worksheets for sales exception reporting and then updates several key points in sales data.

That's a heavy task and if we have a failure on per say in the excel export from a SQL Task that just selects some data, do we really want to forego the update? No, not really sense the update is key to the business running.

So SQL Server 2005 and up implemented a long awaited method of emailing without the need for one of outlook to be installed and or xp_ to use cdonts which opened our instances to security risks. To be honest there were dozens of points on SQL Server 2005 that made the hair on my neck stand up with excitement and this was on the top of the list.

So let's first setup you instance for database mail abilities. First you'll have to verify that database mail is enabled. you can do that with surface area configuration by going into the surface area configuration features. Then select Database Mail and make sure it is Enabled. Remember by default most of SQL Server 2005 features are disabled. You can also run

  1. USE Master
  2. GO
  3. SP_CONFIGURE 'show advanced options', 1
  4. GO
  5. RECONFIGURE WITH override
  6. GO
  7. SP_CONFIGURE 'Database Mail XPs', 1
  8. GO
  9. RECONFIGURE
  10. GO
  11. SP_CONFIGURE 'show advanced options', 0
  12. GO

Now you're going to need a profile and account. Out of scope for me to go step by step through this process and there are hundreds of articles out there on how to do it. Probably hundreds on doing what I'm talking about also but what's the internet if it isn't full of repeated articles stating the same thing ;) One thing I do like to do is create a profile named "DBA {instance name}" and an account to match that naming. This way I know where it comes from and which aspect of the instance is sending it without even opening the mail. At least it gets me to open it quicker than most that is.

So now that you have that all running you can test it by this simple little script

  1. EXEC msdb.dbo.sp_send_dbmail @recipients='you@yourcompany.com',
  2. @subject = 'My Test Email',
  3. @body = 'It works!',
  4. @profile_name = 'SQL DBA'

You should have received the email. I you didn't you can either wait for me to write a troubleshooting database mail blog or following yourself to http://msdn.microsoft.com/en-us/library/ms188663.aspx

Typically if it doesn't work you're blocking it on the server level or at the mail server level. Good thing to check is port blocking and or your companies chosen firewall/antivirus software.

OK this is cool! I can email all kinds of things. Actually you would be very surprised. You can send attachments on the fly, query results, HTML formatting, excel formatting and the list goes on. These all reasons I was excited to see the advent of database mail.

I would take some time and read on the sp_send_dbmail proc http://msdn.microsoft.com/en-us/library/ms190307.aspx

So for a simple job notification and example of what you can do we can create something that has one main process, a success notification and a failure notification.

First create a new job. Then add a step. Something like this

  1. USE [msdb]
  2. GO
  3. BEGIN TRANSACTION
  4. DECLARE @ReturnCode INT
  5. SELECT @ReturnCode = 0
  6.  
  7. IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'[Uncategorized (Local)]' AND category_class=1)
  8. BEGIN
  9. EXEC @ReturnCode = msdb.dbo.SP_ADD_CATEGORY @CLASS=N'JOB', @type=N'LOCAL', @name=N'[Uncategorized (Local)]'
  10. IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
  11.  
  12. END
  13.  
  14. DECLARE @jobId BINARY(16)
  15. EXEC @ReturnCode = msdb.dbo.SP_ADD_JOB @job_name=N'Test Notifications',
  16.   @enabled=1,
  17.   @notify_level_eventlog=0,
  18.   @notify_level_email=0,
  19.   @notify_level_netsend=0,
  20.   @notify_level_page=0,
  21.   @delete_level=0,
  22.   @description=N'Delete this sometime soon to clean up',
  23.   @category_name=N'[Uncategorized (Local)]',
  24.   @owner_login_name=N'{owner}', @job_id = @jobId OUTPUT
  25. IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
  26.  
  27. EXEC @ReturnCode = msdb.dbo.SP_ADD_JOBSTEP @job_id=@jobId, @step_name=N'Caller Task',
  28.   @step_id=1,
  29.   @cmdexec_success_code=0,
  30.   @on_success_action=4,
  31.   @on_success_step_id=2,
  32.   @on_fail_action=4,
  33.   @on_fail_step_id=3,
  34.   @retry_attempts=0,
  35.   @retry_interval=0,
  36.   @os_run_priority=0, @subsystem=N'TSQL',
  37.   @command=N'Select 1',
  38.   @database_name=N'DBA',
  39.   @flags=0
  40. IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
  41.  
  42. EXEC @ReturnCode = msdb.dbo.SP_ADD_JOBSTEP @job_id=@jobId, @step_name=N'Success Caller',
  43.   @step_id=2,
  44.   @cmdexec_success_code=0,
  45.   @on_success_action=1,
  46.   @on_success_step_id=0,
  47.   @on_fail_action=4,
  48.   @on_fail_step_id=3,
  49.   @retry_attempts=0,
  50.   @retry_interval=0,
  51.   @os_run_priority=0, @subsystem=N'TSQL',
  52.   @command=N'Declare @sub varchar(1000)
  53. Declare @bd varchar(2000)
  54.  
  55. Set @sub = ''Success on SQL Agent '' + @@servername
  56. Set @bd = ''Success on SQL Agent '' + @@servername + '' for job task caller task at + getdate() + '' requiring no attention so go back to sleep''
  57.  
  58. EXEC msdb.dbo.sp_send_dbmail @recipients=''you@yourcompany.com'',
  59. @subject = @sub,
  60. @body = @bd,
  61. @profile_name = ''SQL DBA''
  62. ',
  63.   @database_name=N'msdb',
  64.   @flags=0
  65. IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
  66.  
  67. EXEC @ReturnCode = msdb.dbo.SP_ADD_JOBSTEP @job_id=@jobId, @step_name=N'Failure Caller',
  68.   @step_id=3,
  69.   @cmdexec_success_code=0,
  70.   @on_success_action=2,
  71.   @on_success_step_id=0,
  72.   @on_fail_action=2,
  73.   @on_fail_step_id=0,
  74.   @retry_attempts=0,
  75.   @retry_interval=0,
  76.   @os_run_priority=0, @subsystem=N'TSQL',
  77.   @command=N'Declare @sub varchar(1000)
  78. Declare @bd varchar(2000)
  79.  
  80. Set @sub = ''Failure on SQL Agent '' + @@servername
  81. Set @bd = ''Failure on SQL Agent '' + @@servername + '' occurred at + getdate() + '' requiring immediate attention''
  82.  
  83. EXEC msdb.dbo.sp_send_dbmail @recipients=''you@yourcompany.com'',
  84. @subject = @sub,
  85. @body = @bd,
  86. @profile_name = ''SQL DBA''',
  87.   @database_name=N'msdb',
  88.   @flags=0
  89. IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
  90. EXEC @ReturnCode = msdb.dbo.SP_UPDATE_JOB @job_id = @jobId, @start_step_id = 1
  91. IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
  92. EXEC @ReturnCode = msdb.dbo.SP_ADD_JOBSERVER @job_id = @jobId, @server_name = N'(local)'
  93. IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
  94. COMMIT TRANSACTION
  95. GOTO EndSave
  96. QuitWithRollback:
  97. IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
  98. EndSave:

You can test this job to see how it works by running as is and also changing the mail "Caller Task" so something like select 1/0.

Obviously I like the right click script option. The important things you need to know here is the workflow sense I'm sure if you're reading this you know how to create a SQL Job already and don't need me to tell you how.

The main task will require you to push to the successful notification upon a successful run and then the failure on that event. So in SSMS you're going to have it look like this

Make sure you use your successful notification task in the On success action or you're job will have an unreachable task and complain when you save it. Then make sure your Success Caller reports success but if failure points to the failure caller task. In your failure task your always going to want to report failure on success. So you're other tasks advanced options will appear as

Success...

Failure...

I also recommend notification services and setting up the normal failure notifications in the SQL job. This way if all fails you should get it queued up.

So now you can email to your heart's content. Well until you show up on the black list anyhow ;)

About the Author

Ted Krueger has been working in development and database administration for 13+ years. Specialties range from High Availability and Disaster / Recovery setup and testing methods down to custom assembly development for SQL Server Reporting Services. Ted blogs and is also one of the founders of LessThanDot.com technology community. Some of the articles focused on are Backup / Recovery, Security, SSIS and working on SQL Server and using all of the SQL Server features available to create stable and scalable database services. Recent community contributions have been to organize SQL Saturday events in the Chicago-land to Milwaukee-land area for 2010 where he will also be speaking about various SQL Server topics. @onpnt
Social SitingsTwitterLinkedInLTD RSS Feed
2551 views
submit to reddit Digg!FacebookDotnetkicks

Comments and Feedback

3 comments

Comment from: Jerry Hung [Visitor] · http://www.SQLServerNewbie.com
Sorry for asking

How is this different than setting up "Notifications" in the "Job Properties" window?
Choices of Email/Pager/Net Send... without T-SQL code

Provided, I think one needs to setup Database Mail for the mail server
01/12/08 @ 11:58
Comment from: onpnt [Member] Email
In my example it differs in no way at all. In what I tried to get across though is in most jobs you're going to have tasks that are not per say required to pass in order to complete the next tasks. In the discussion I was bringing up there was a download task, insert task, select into report task and critical update task. Say your report task fails but it's something that is not critical and you can run it real-time next business day but if that task fails and your job exits without the update you're in deep. That alone can be handled with error handling in the job but you may not to be notified from the sql task that you are required to do this.
basically what this gives you is free hand notifications in the coding and tasks. It may have been missleading providing a compelte task just for sending notifications. think of the tasks within the others


And please don't be sorry for asking. I am more than open to someone saying, "Man this is dumb. Just do this..." That's how we grow into better people at our jobs :)
01/12/08 @ 12:05
Comment from: how to write management report [Visitor] · http://www.mindrs.com/mindrs/?p=157
thank you for this good article
02/12/08 @ 01:12

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)