Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Agent Job - Exists then Drop?

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] ... 
like image 627
madcolor Avatar asked Sep 25 '08 23:09

madcolor


People also ask

How do I drop a SQL Agent job?

Using SQL Server Management StudioExpand SQL Server Agent, expand Jobs, right-click the job you want to delete, and then click Delete. In the Delete Object dialog box, confirm that the job you intend to delete is selected. Click OK.

Why did a SQL Server Agent job fail?

Similar to Windows services, SQL Agent Jobs run under a user or service account configured in the job. Job failures can occur when there are permission or authentication issues with the user or service account. Common issues include: Account expired.

How do I fix SQL Server Agent stopped automatically?

Check the SQL error log for any related stack dumps or messages. This exception forces SQL Server to shutdown. To recover from this error, restart the server (unless SQLAgent is configured to auto restart).

What is @schedule_uid?

The gottcha lies in that schedule_uid. If you create another job schedule with the same schedule_uid, it will overwrite the schedule for any jobs that are using it. i.e. Any other jobs that are using that schedule_uid will start using the new schedule.


2 Answers

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'

like image 152
Codewerks Avatar answered Oct 12 '22 06:10

Codewerks


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 
like image 44
Seshu Avatar answered Oct 12 '22 06:10

Seshu