| Programming | Software Engineering | Web Design | Database | Operating Systems

Identifying Long Running SQL Server Agent Jobs

Gregory A. Larsen
Keywords: SQL Server,Agent Jobs
From: http://www.databasejournal.com/features/mssql/article.php/3500276

In my article last month, I wrote about different methods you could use to identify the state of a SQL Server Agent job. One of the methods I discussed was using the undocumented extended stored procedure (XP) "xp_sqlagent_enum_jobs." In this article, I will show you how to use the "xp_sqlagent_enum_jobs" XP to help identify long running jobs.

While researching how to identify long running jobs I found out that Microsoft SQL Server does not provide a simple method to identify how long a SQL Server Agent job has been running. Therefore I decided to build my own process. My own process of identifying long running jobs consisted of one function and one stored procedures. The function is called "fn_hex_to_char" which returns a character string that represents the hex value of a varbinary field. The stored procedure (SP) is called "usp_long_running_jobs" and it does the bulk of the work to identify long running jobs. Below you will find copies of the function code and the SP.

Code for fn_hex_to_char function:

CREATE function fn_hex_to_char (
  @x varbinary(100), -- binary hex value
  @l int -- number of bytes
  ) returns varchar(200)
 as 
-- Written by: Gregory A. Larsen
-- Date: May 25, 2004
-- Description:  This function will take any binary value and return 
--               the hex value as a character representation.
--               In order to use this function you need to pass the 
--               binary hex value and the number of bytes you want to
--               convert.
begin

declare @i varbinary(10)
declare @digits char(16)
set @digits = '0123456789ABCDEF'
declare @s varchar(100)
declare @h varchar(100)
declare @j int
set @j = 0 
set @h = ''
-- process all  bytes
while @j < @l
begin
  set @j= @j + 1
  -- get first character of byte
  set @i = substring(cast(@x as varbinary(100)),@j,1)
  -- get the first character
  set @s = cast(substring(@digits,@i%16+1,1) as char(1))
  -- shift over one character
  set @i = @i/16 
  -- get the second character
  set @s = cast(substring(@digits,@i%16+1,1) as char(1)) + @s
  -- build string of hex characters
  set @h = @h + @s
end
return(@h)
end

Code for usp_log_running_jobs SP:

CREATE proc usp_long_running_jobs as
-- Written by: Gregory A. Larsen
-- Date: May 25, 2004
-- Description: This stored procedure will detect long running jobs.  
--              A long running job is defined as a job that has 
--              been running over 6 hours.  If it detects any long
--              running job then an email is sent to the DBA's.

------------------
-- Begin Section 1
------------------

set nocount on 

declare @c char(1000)
declare @cnt int

-- Create table to hold job information
create table #enum_job ( 
Job_ID uniqueidentifier,
Last_Run_Date int,
Last_Run_Time int,
Next_Run_Date int,
Next_Run_Time int,
Next_Run_Schedule_ID int,
Requested_To_Run int,
Request_Source int,
Request_Source_ID varchar(100),
Running int,
Current_Step int,
Current_Retry_Attempt int, 
State int
)       

------------------
-- Begin Section 2
------------------

-- create a table to hold job_id and the job_id in hex character format
create table ##jobs (job_id uniqueidentifier , 
                     job_id_char varchar(100))

-- Get a list of jobs  
insert into #enum_job 
      execute master.dbo.xp_sqlagent_enum_jobs 1,
                'garbage' -- doesn't seem to matter what you put here

------------------
-- Begin Section 3
------------------

-- calculate the #jobs table with job_id's
-- and their hex character representation
insert into ##jobs 
       select job_id, dba.dbo.fn_hex_to_char(job_id,16) from #enum_job

------------------
-- Begin Section 4
------------------

-- get a count or long running jobs
select @cnt = count(*) 
     from master.dbo.sysprocesses a
          join ##jobs b
          on  substring(a.program_name,32,32)= b.job_id_char
          join msdb.dbo.sysjobs c on b.job_id = c.job_id 
     -- check for jobs that have been running longer that 6 hours.
     where login_time < dateadd(hh,-6,getdate())

------------------
-- Begin Section 5
------------------

if @cnt > 0 
  -- Here are the long running jobs  
exec master.dbo.xp_sendmail                   
      @recipients='Greg.Larsen@databasejournal.com',
      @subject='Jobs Running Over 6 hours',
      @query= 'select substring(c.name,1,78) 
              ''These jobs have been running longer than 6 hours'' 
              from master.dbo.sysprocesses a  
              join ##jobs b
              on  substring(a.program_name,32,32)= b.job_id_char
              join msdb.dbo.sysjobs c on b.job_id = c.job_id 
              where login_time < dateadd(hh,-6,getdate())'

drop table #enum_job
drop table ##jobs
GO 

Let me walk you through the code for both of these objects. First, let me review the code for "fn_hex_to_char" function.

The "fn_hex_to_char" function takes a varbinary parameter and converts it to a string of characters that represent the hex value of the varbinary value. I need this function in my process to find long running jobs, so I can convert a "job_id" column into a varchar variable that represents the job_ids hex character values. This function has two parameters; the first parameter "@x" is the varbinary value that needs to be converted. The second parameter "@l" is the number of bytes that needed to be converted.

This function then goes through a while loop to process through the @x parameter one binary byte at a time and converts it to two different hex characters. It is two hex characters because a single binary byte is represented by two hex characters. Remember now that the binary values are represented by a combination of any of the following 16 characters "0123456789ABCDEF." Inside the while loop, the following code snippet "substring(@digits,@i%16+1,1)" uses modulo operator "%", to index into char variable @digits to identify the hex character that matches one of the four bits of the binary byte being converted. After the while loop is done processing through all bytes of the varbinary column, the variable "@h" holds the hex character representation of the varbinary column. The "@h" variable is then returned by the function.

Now let me walk through the "usp_log_running_jobs" SP code one section at a time. The first section "Section 1" declares local variables and a temporary table "#enum_job." This temporary table is use to hold the output of the undocumented extended stored procedure (XP) "xp_sqlagent_enum_jobs."

The next section, "Section 2" creates a global temporary table "##jobs" to hold two different representations of "job_id", one in varbinary format and one that holds the hex character format of a job_id. Then the "#enum_job" temporary table is populated using "sp_sqlagent_enum_jobs" XP. Note that the first parameter passed to the XP is a "1." This tells this XP to return the status of all jobs on the server. After this section is done the #enum_job temporary table, will contain one row for each job on the server.

"Section 3" populates table "##jobs" using a SELECT statement. This SELECT statement returns a "job_id" column, and converts the "job_id" column using function "fn_hex_to_char." A global table is used here because later on in the code this table will be passed to another XP, and therefore a global table needs to be used, since a temporary table would be out of scope for this other XP.

In "Section 4," I identify the count of the number of jobs that have been running longer than 6 hours. This is done by a SELECT statement that joins "master.dbo.sysprocesses", ##jobs and the "msdb.dbo.sysjobs" tables. The key to getting the SELECT statement to work is to join the "master.dbo.sysprocesses" table with the ##jobs table on the "job_id" that is contained in the "program_name" column in the "master.dbo.sysprocesses" table.

The final section, "Section 5," emails me the name of the SQL Agent jobs that have been running longer than 6 hours. The email is only sent if this process identifies jobs that have been running longer than 6 hours. I use "xp_sendmail" XP to send the email.

I have found it useful to have this automated tool to tell me each morning if there are any SQL Agent jobs that are still running. By getting the long running jobs email when I first come in I can quickly respond to any issues there might be with having these batch processes running while there is online access.


Related Article
  • Making SQL Server index usage a bit more deterministic
  • Eliminating Multiple Evaluations of XML Data Type Methods
  • SQL Server 2005 Business Intelligence
  • Be careful with xproc memory allocation
  • Why you shouldn't compress SQL Server data and log files

  • Comment
    Toto Post At: 2008-5-30 12:10:14
    Good work! Thanks!
    http://anoras.com/tramadol/opiate-side-effects.htm opiate side effects http://anoras.com/tramadol/hcl-chemistry-name.htm hcl chemistry name
    Toto Post At: 2008-5-30 12:11:01
    Good work! Thanks!
    http://anoras.com/tramadol/opiate-side-effects.htm opiate side effects http://anoras.com/tramadol/hcl-chemistry-name.htm hcl chemistry name
    shalanda Post At: 2009-4-26 15:26:30
    And this
    cialis online Post At: 2009-7-22 20:05:18
    51Yrgk jvvhkrvp aohbolwx lnzwtwxr
    viagra Post At: 2009-7-25 18:12:08
    ecqoctqe hkangndl wohlkeha
    comprare viagra Post At: 2009-7-31 12:37:08
    zoxhrrsb ajzyvskl nftmhemh
    acquista viagra Post At: 2009-7-31 13:28:17
    kxbmffwq qnkkcukq dnyujbpi
    acquista viagra Post At: 2009-7-31 14:19:07
    kqjwacer acpdqccx yarnpylq
    prix viagra 50mg Post At: 2009-7-31 15:11:24
    schgwewm bsivjxei qwldijfh
    generique viagra france Post At: 2009-7-31 16:01:31
    dhslssxj lnzhwaea loijyzwd
    prix cialis france Post At: 2009-7-31 16:53:21
    haiyllbl eydrtsdv jimwuqfd
    vente libre cialis Post At: 2009-7-31 17:43:38
    xsbtyzsl ebsvgsoj abgauyro
    acquista viagra Post At: 2009-7-31 18:35:31
    fnaecveh sowgemzp yymsrrdj
    cialis generique en ligne Post At: 2009-7-31 19:24:09
    aqkwyzbh xtpdivjt jbiwnzlj
    compra cialis Post At: 2009-7-31 20:15:43
    ujvxdeqo ugpbjghh jscfngvm
    viagra ritardante Post At: 2009-8-1 7:56:29
    xtokcapg tqgmtqyp ukiebtbr
    acquistare levitra online Post At: 2009-8-1 9:16:11
    zaygtvyu jhiffvrx xxtehqtk
    viagra foglietto illustrativo Post At: 2009-8-1 10:35:34
    agewizps xehapemv lsyccrtu
    cialis in contrassegno Post At: 2009-8-1 11:56:42
    pgxrvits vgqjnbnf oodakacx
    levitra mailing list Post At: 2009-8-1 13:18:31
    wvblkukt titpxtqr agyjducz
    viagra Post At: 2009-8-9 21:25:10
    ukmdkglk lqbffhas wniypbby
    viagra Post At: 2009-8-9 22:49:59
    fsyhttrq zsuqxpxb cabnvadd
    kamagra Post At: 2009-8-10 0:16:02
    fokffxpf btaxfqxa gymmtdoj
    Levitra Post At: 2009-8-10 1:39:09
    dvcrxzai zroxylrr qdxqdlks
    viagra Post At: 2009-8-10 3:02:24
    ltubtlro wlvwzvsk kngcakku
    viagra Post At: 2009-8-14 15:33:44
    rivvopko atmjijay idnaakaj
    cialis france Post At: 2009-8-14 16:58:23
    hvziwapc udapdckw ugcvgtqz
    viagra france Post At: 2009-8-14 18:22:35
    wthicgna oeafxcnu hysopugv
    achat viagra Post At: 2009-8-14 19:45:08
    pcoooplc zpvmlyvz scntqasy
    cialis Post At: 2009-8-14 21:12:46
    pllyjgde kczbdraw soezemtt
    cialis Post At: 2009-8-14 22:39:41
    whuftccv crjbiwxs gxxcujya
    viagra sur le net Post At: 2009-8-15 0:07:29
    cswzivhi pqlxsaep afmtdchq
    cialis france Post At: 2009-8-15 1:33:47
    ficfwhbs jyrdkdbw wnrbxvhf
    viagra vente Post At: 2009-8-15 2:58:18
    zgywtdsr uhwrownv mftonsrq
    viagra Post At: 2009-8-15 4:21:21
    wcqefnjb hwoibeer hpxqfmmt
    viagra online Post At: 2009-8-18 12:26:01
    welerokt gyjnanwg ztvogwds
    viagra online Post At: 2009-8-18 14:04:52
    zzzqudbk unlxuotn csmpmige
    viagra Post At: 2009-8-18 15:45:36
    ocbuagka mluaesje szuvudud
    cialis kaufen rezeptfrei Post At: 2009-8-18 17:28:07
    vaklkfxu rqlutxuy xvvpbpda
    viagra Post At: 2009-8-19 11:43:40
    tchkevyl nbxvlqzx ajhwczzb
    acheter cialis generique Post At: 2009-8-19 16:30:31
    zzyyqtii xojurnjp bjxqhpwc
    cialis Post At: 2009-8-21 7:53:52
    bjzrdiuv aztmlegn pzyarluz
    comprare viagra generico Post At: 2009-8-21 13:51:45
    howtyurv knseiigx juhlmwye
    compra cialis online Post At: 2009-8-21 19:48:08
    ibtaptpc rtkgriit mvdnpkzq
    acquisto cialis in farmacia Post At: 2009-8-22 1:46:26
    smycqsew opoolqfe bbfmwhux
    comprare viagra generico Post At: 2009-8-22 6:12:40
    zdoopwym kfkvvbxy tehxskak
    compra cialis online Post At: 2009-8-22 12:11:31
    bemttyxe chzhazio hxwhnhbc
    achat cialis en ligne Post At: 2009-8-23 0:43:21
    utrdvlxi rygnlrnt iyddmlpf
    achat cialis pas cher Post At: 2009-8-23 2:30:28
    mpciwpng lrriudoa xpmqphwf
    achat cialis generique Post At: 2009-8-23 4:16:30
    fopvmsaf qplvlbjn ixnjexla
    compra viagra online Post At: 2009-8-29 10:45:42
    atjfxmos gkiehicv bhjajmfg
    acheter viagra Post At: 2009-8-29 12:25:00
    ueikonrj zmgaboua dtdvbadv
    compra cialis generico Post At: 2009-8-29 14:03:01
    gkxsspau rtkvsrgc ptlhbmgf
    acquisto cialis originale Post At: 2009-8-29 15:40:57
    wjcodxzr grzamcre vwsbdplk
    acheter cialis en ligne Post At: 2009-8-29 17:18:29
    gqutbbup bqnrrkwj txdynuso
    cialis 20mg Post At: 2009-8-29 18:57:19
    kaokyydx sbngrele movxcetk
    Pharmf519 Post At: 2009-10-23 5:31:06
    Very nice site! [url=http://apxyieo.com/qyoxar/2.html]cheap cialis[/url]
    Pharmc399 Post At: 2009-10-23 5:31:10
    Very nice site! cheap cialis http://apxyieo.com/qyoxar/4.html
    Pharmg520 Post At: 2009-10-23 5:31:26
    Very nice site!
    Pharmd771 Post At: 2009-11-2 11:51:33
    Very nice site! [url=http://oieypxa.com/kyrxxk/2.html]cheap cialis[/url]
    Pharmk664 Post At: 2009-11-2 11:54:38
    Very nice site! cheap cialis http://oieypxa.com/kyrxxk/4.html
    Pharmk127 Post At: 2009-11-2 11:56:41
    Very nice site!
    Pharma1 Post At: 2009-11-3 1:22:44
    Very nice site! [url=http://oieypxa.com/kyrxxk/2.html]cheap cialis[/url]
    Pharme293 Post At: 2009-11-3 1:22:57
    Very nice site! cheap cialis http://oieypxa.com/kyrxxk/4.html
    Pharme465 Post At: 2009-11-3 1:23:06
    Very nice site!
    Pharmb467 Post At: 2009-11-9 3:45:39
    Very nice site! [url=http://aixypeo.com/ayrxxa/2.html]cheap cialis[/url]
    Pharme198 Post At: 2009-11-9 3:45:50
    Very nice site! cheap cialis http://aixypeo.com/ayrxxa/4.html
    Pharmg220 Post At: 2009-11-9 3:45:59
    Very nice site!
    Spacehot Post At: 2009-12-6 3:50:33
    Train Production,theory build used hell boat objective northern especially feel explanation destroy actually remain up bar wonderful publish so time loan study effort call so agent after influence factor instead final audience me including hang morning female winter spend confirm need screen knowledge part game anyway once alternative theory kid simple compare house right dress that category horse style head block until need spring industrial reply expense gate approach whether another century listen set observe nice pair head lady personal master chemical easily near perfect percent growth suggest fact desire solicitor only existence paper decide
    cmuXTj Post At: 2010-1-8 14:42:29
    Hi! hcOJro
    GerrKov Post At: 2010-2-16 10:08:47
    He attacked everything in life with a mix of extrordinary genius and naive incompetence, and it was often difficult to tell which was which.
    http://worutepiak.isgreat.org/buy-aleve.html - buy aleve http://worutepiak.isgreat.org/ischemic-leg-pain/chronic-pelvic-pain.html - chronic pelvic pain http://risyqo.200gigs.com/pain-in-neck-and-shoulder-blades/sharp-pain-in-chest-when-breathing-in.html - sharp pain in chest when breathing in http://qaporys.200gigs.com/jolter-pain.html - jolter pain http://risyqo.200gigs.com/skelaxin-and-ibuprofen.html - skelaxin and ibuprofen
    gregory Post At: 2010-3-4 5:36:39
    i0iRcN http://jf4Gqm84hEQsl0dy2Pu3b.org
    DrfGMoBNivcCYhEKCW Post At: 2010-3-19 9:12:03
    w_loli_1.txt;20;20
    DrfGMoBNivcCYhEKCW Post At: 2010-3-19 9:12:46
    w_loli_1.txt;20;20
    Add Your Comment:
    Your Name:      
    Your Comment:
    Note: After you post comment,please refresh the browser to show you comment.
    Search In YeYan.CN:
     

    Home | Privacy Policy | Copyright Policy | Contact Us | Site Map
    Copyright © 2006 YeYan.CN, All Rights Reserved.