Pages

Mar 26, 2018

Tracking long running SQL Server Agent jobs

Hi Guys,

It is very important to monitor the long running SQL jobs in production environments and it is cannot miss task of every SQL DBA.

I use below query to catch the long running jobs.

SQL job is created with this query and scheduled to run every 3hrs. which sends notifications of jobs which are running from more than 30mins. You can make it how ever is required to your environment.


USE [msdb]
GO


SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[usp_LongRunningJobNotification]
     @Minutes int
AS
BEGIN

set nocount on
declare @ThresholdMinutes int
  select @ThresholdMinutes = case when isnull(@Minutes,0) < 1
                                       then 1
                                  when isnull(@Minutes,0) > 120
                                                              then 120
                                                         else @Minutes
                                                 end
if (
  select max(datediff(ss,ja.start_execution_date,getdate()))
    from msdb.dbo.sysjobactivity ja,msdb.dbo.sysjobs jm
   where 1=1
     and datediff(ss,ja.start_execution_date,getdate()) > @ThresholdMinutes*60
     and jm.job_id = ja.job_id
        and jm.category_id = 0
        and jm.enabled = 1
        and jm.name != 'BlockingHistoryCapture'
     and ja.stop_execution_date is null
     and ja.start_execution_date is not null
     and not exists(  select 'x'
                        from msdb.dbo.sysjobactivity new
                       where new.job_id = ja.job_id
                         and new.start_execution_date > ja.start_execution_date)
   ) > @ThresholdMinutes*60
begin -- If long running job
      create table ##LongRunningJobsTemp
         ( jobname nvarchar(128) not null,
           ExecutionDate varchar(19),
           MinutesExecuting varchar(8)
         )
        insert
                into ##LongRunningJobsTemp
        select rtrim(substring(jm.name,1,64)) Jobname,
               convert(varchar(10),ja.start_execution_date,101)+' '+convert(varchar(8),ja.start_execution_date,114) ExecutionDate,
               convert(varchar(8),getdate()-ja.start_execution_date,114) MinutesExecuting
          from msdb.dbo.sysjobactivity ja,msdb.dbo.sysjobs jm
         where 1=1
           and datediff(ss,ja.start_execution_date,getdate()) > @ThresholdMinutes*60
           and jm.job_id = ja.job_id
           and jm.category_id = 0
           and jm.enabled = 1
                 and jm.name != 'BlockingHistoryCapture'
           and ja.stop_execution_date is null
           and ja.start_execution_date is not null
           and not exists(  select 'x'
                              from msdb.dbo.sysjobactivity new
                             where new.job_id = ja.job_id
                              and new.start_execution_date > ja.start_execution_date)
      order by jm.name
      set nocount off
      if (select count(*) from ##LongRunningJobsTemp) > 0

         begin -- If temp table has any rows

               DECLARE @tableHTML  NVARCHAR(MAX) ;

SET @tableHTML =  '<html><head>' +
                             '<style>' +
                             'H1 {margin-left:100px;padding-left:7px;font-size:18pt;font-family:calibre;color:Black}' +
                  'th {font-family:calibre;background-color:#DB7093;border: solid black 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:12pt;} ' +
                  'td {font-family:calibre;background-color:#DB7093;border: solid black 1px;padding-left:5px;padding-right:5px;padding-top:1px;padding-bottom:1px;font-size:12pt;} ' +
                  '</style>' +
                  '</head>' +
                             '<Body>'  +
    N'<H1>Long Running Job Alert!</H1>' +
    N'<table border="1">' +
    N'<th>JobName</th>' +
       N'<th>ExecutionDate</th>' +
       N'<th>MinutesExecuting</th>' +
       CAST ( ( SELECT td = lr.Jobname, '',
                                  td = Lr.ExecutionDate, '',
                    td = Lr.MinutesExecuting, ''
                                  FROM ##LongRunningJobsTemp as lr
              FOR XML PATH('tr'), TYPE
    ) AS NVARCHAR(MAX) ) +
    N'</table>' ;

declare @email_address varchar(100)
select @email_address =email_address from dbo.sysoperators where name='LongRunningJob_Notification'


                   exec msdb.dbo.sp_send_dbmail
                    @profile_name = 'JobMail',
                    @subject='ServerName: Long Running Job Alert!',
                    @recipients= @email_address,
                    @body=@tableHTML,
                    @body_format='HTML'

      drop table ##LongRunningJobsTemp
end -- If long running job
end
END


Note: Make sure you create your own operator and use it.

35 comments:

  1. It has been simply incredibly generous with you to provide openly what exactly many individuals would’ve marketed for an eBook to end up making some cash for their end, primarily given that you could have tried it in the event you wanted
    full stack developer training in chennai

    ReplyDelete
  2. Some us know all relating to the compelling medium you present powerful steps on this blog and therefore strongly encourage contribution from other ones on this subject while our own child is truly discovering a great deal. Have fun with the remaining portion of the year.
    AWS Training in chennai

    AWS Training in bangalore

    ReplyDelete
  3. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

    Data Science Training in Chennai
    Data science training in bangalore
    Data science online training
    Data science training in pune

    ReplyDelete
  4. You made such an interesting piece to read, giving every subject enlightenment for us to gain knowledge. Thanks for sharing the such information with us

    angularjs Training in chennai
    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    ReplyDelete
  5. I believe there are many more pleasurable opportunities ahead for individuals that looked at your site.
    python interview questions and answers | python tutorialspython training institute in electronic city

    ReplyDelete
  6. Awesome and very useful blog. A great and very informative post, Keep up the good work!


    Data Science Courses in Bangalore

    ReplyDelete
  7. It should be noted that whilst ordering papers for sale at paper writing service, you can get unkind attitude. In case you feel that the bureau is trying to cheat you, don't buy term paper from it.
    ExcelR Data science courses in Bangalore

    ReplyDelete
  8. i am for the first time here. I found this board and I in finding It truly helpful & it helped me out a lot. I hope to present something back and help others such as you helped me.
    big data course malaysia

    ReplyDelete
  9. I was just browsing through the internet looking for some information and came across your blog. I am impressed by the information that you have on this blog. It shows how well you understand this subject. Bookmarked this page, will come back for more.
    data science course in singapore

    ReplyDelete
  10. I am looking for and I love to post a comment that "The content of your post is awesome" Great work!
    pmp certification malaysia

    ReplyDelete
  11. SSC Result 2020 Published Date & Time by ssc result
    ssc result 2020
    Education Board of Bangladesh.
    Many of You Search For SSC Result Kobe Dibe on Internet
    as Well as Facebook. The results of Secondary School Certificate
    (SSC)—and its equivalent examinations—for 2020 have been published.
    SSC & Dakhil Result 2020 Published Date is Very Important For T
    he Students Who Attend The SSC Exam 2020.

    ReplyDelete
  12. These provided information was really so nice,thanks for giving that post and the more skills to develop after refer that post thnska a lot guys.
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  13. Somebody who need windows key click: www.vanskeys.com to got. here i got a working key on my windows about activator. and after i used my windows works properly. hope it help you.Thanks lot!!

    Android Training in Chennai

    Android Online Training in Chennai

    Android Training in Bangalore

    Android Training in Hyderabad

    Android Training in Coimbatore

    Android Training

    Android Online Training

    ReplyDelete
  14. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...data science courses

    ReplyDelete
  15. Very nice blogs!!! i have to learning for lot of information for this sites…Sharing for wonderful information.Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing, data scientist course in hyderabad with placement

    ReplyDelete
  16. Thanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area. data science training in Hyderabad

    ReplyDelete
  17. Through this post, I know that your good knowledge in playing with all the pieces was very helpful. I notify that this is the first place where I find issues I've been searching for. You have a clever yet attractive way of writing.
    machine learning courses in bangalore

    ReplyDelete
  18. I am truly getting a charge out of perusing your elegantly composed articles. It would seem that you burn through a ton of energy and time on your blog. I have bookmarked it and I am anticipating perusing new articles. Keep doing awesome.
    data scientist training and placement

    ReplyDelete
  19. Pleasant data, important and incredible structure, as offer great stuff with smart thoughts and ideas, loads of extraordinary data and motivation, the two of which I need, because of offer such an accommodating data here.
    business analytics course in hyderabad

    ReplyDelete
  20. Nice blog and informative content. I am impressed a lot with your blog. Keep up your work in further blogs.
    Data Scientist Training in Hyderabad

    ReplyDelete
  21. They're produced by the very best degree developers who will be distinguished for your polo dress creation. You'll find Ron Lauren inside an exclusive array which includes particular classes for men, women.
    business analytics training in hyderabad

    ReplyDelete
  22. It is the perfect time to make some plans for the future and it is the time to be happy. I've read this post and if I could I would like to suggest some interesting things or suggestions. Perhaps you could write the next articles referring to this article. I want to read more things about it!
    data analytics course in hyderabad

    ReplyDelete
  23. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post.
    data analytics courses in hyderabad

    ReplyDelete
  24. These methods allow for proactive monitoring and troubleshooting of SQL Server Agent jobs to maintain optimal performance.

    Data science courses in Pune

    ReplyDelete
  25. Offers guidance on how to track long-running SQL Server Agent jobs and monitor their performance.
    Data science courses in the Netherlands

    ReplyDelete
  26. "Fantastic post! Tracking long-running SQL Server Agent jobs can be tricky, but your guide makes it much easier. The step-by-step process and your detailed explanation of how to set up alerts are very useful for database administrators. I’ll be using this in my daily work. Thanks for the valuable tips!"
    Data science courses in Glasgow

    ReplyDelete
  27. This is a practical and efficient way to monitor long-running SQL jobs, especially in production environments. Scheduling it every 3 hours is a great idea!
    Data science Courses in City of Westminster

    Neel KBH
    kbhneel@gmail.com

    ReplyDelete
  28. Tracking long-running SQL Server agent jobs can be challenging, but this article simplifies the process with clear instructions and useful tips. Highly recommended for database administrators!

    Data science courses in France

    ReplyDelete
  29. Thank you for the informative blog. Keep sharing the good content.
    Data Analytics Courses In Chennai

    ReplyDelete
  30. This is a really useful guide for SQL Server management. Long-running jobs can be so frustrating to track, but your tips on monitoring them are spot on. I’ll be using these techniques in my next project. Thanks for the helpful post
    Top 10 Digital marketing courses in pune

    ReplyDelete