68

How can I drop sql server agent jobs, if (and only if) it exists?

This is a well functioning script for stored procedures. How can I do the same to sql server agent jobs?

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[storedproc]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
    drop procedure [dbo].[storedproc]
GO
CREATE PROCEDURE [dbo].[storedproc] ...
madcolor
  • 8,105
  • 11
  • 51
  • 74

3 Answers3

106

Try something like this:

DECLARE @jobId binary(16)

SELECT @jobId = job_id FROM msdb.dbo.sysjobs WHERE (name = N'Name of Your Job')
IF (@jobId IS NOT NULL)
BEGIN
    EXEC msdb.dbo.sp_delete_job @jobId
END

DECLARE @ReturnCode int
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'Name of Your Job'

Best to read the docs on all the parameters required for 'sp_add_job' and 'sp_delete_job'

NTDLS
  • 4,757
  • 4
  • 44
  • 70
Codewerks
  • 5,884
  • 5
  • 29
  • 33
  • EXEC msdb.dbo.sp_delete_job @job_id should be: EXEC msdb.dbo.sp_delete_job @jobId – madcolor Oct 06 '08 at 15:05
  • When SQL Server management studio generates SQL to check whether the job exists, it uses the view 'msdb.dbo.sysjobs_view'. No idea why, just an observation. – Tom Apr 27 '11 at 00:20
  • 1
    ` EXEC msdb.dbo.sp_delete_job @job_name = @JobName Is a bit easier as you don't have to go from jobname to jobid :shrug: ` – visch Jul 21 '21 at 17:16
25
IF EXISTS (SELECT job_id 
            FROM msdb.dbo.sysjobs_view 
            WHERE name = N'Your Job Name')
EXEC msdb.dbo.sp_delete_job @job_name=N'Your Job Name'
                            , @delete_unused_schedule=1
Pete Carter
  • 2,691
  • 3
  • 23
  • 34
Seshu
  • 251
  • 3
  • 2
2

If you generate the SQL script for a job (tested with enterprise manager), it automatically builds the check for existance and drop statements for you. Example below: -

DECLARE @JobID BINARY(16)   
DECLARE @ReturnCode INT  
SELECT @ReturnCode = 0  
-- Delete the job with the same name (if it exists)  
SELECT @JobID = job_id   
FROM  msdb.dbo.sysjobs  
WHERE (name = N'My test job')   
IF (@JobID IS NOT NULL)  
BEGIN  
-- Check if the job is a multi-server job  
IF (EXISTS (SELECT *   
FROM msdb.dbo.sysjobservers   
WHERE (job_id = @JobID) AND (server_id <> 0)))   
BEGIN   
-- There is, so abort the script   
RAISERROR (N'Unable to import job ''My test job'' since there is already a multi-server   job with this name.', 16, 1) 
END   
ELSE   
-- Delete the [local] job   
EXECUTE msdb.dbo.sp_delete_job @job_name = N'My test job'   
SELECT @JobID = NULL  
END 
Asif
  • 2,657
  • 19
  • 25
Andy Jones
  • 1,472
  • 9
  • 15