Reputation: 1181
Im using SQL Server 2012 and I have a case where I have to delete sql jobs. I found two approaches which are as follows:
Approach 1
DECLARE @jobId binary(16)
WHILE (1=1)
BEGIN
SET @jobId = NULL
SELECT TOP 1 @jobId = job_id FROM msdb.dbo.sysjobs WHERE (name like N'Abc%')
IF @@ROWCOUNT = 0
BREAK
IF (@jobId IS NOT NULL)
BEGIN
EXEC msdb.dbo.sp_delete_job @jobId
END
END
Approach 2
DECLARE @listStr VARCHAR(MAX)=null
SELECT @listStr = COALESCE(@listStr+'exec msdb.dbo.sp_delete_job ' ,'') + '''' + convert(varchar(max),job_id) + '''; '
FROM msdb.dbo.sysjobs WHERE (name like N'$(TestPublisherServer)-$(TestPublisherDB)%')
IF @listStr is not null
BEGIN
PRINT 'exec msdb.dbo.sp_delete_job ' + @listStr
EXEC ('exec msdb.dbo.sp_delete_job ' + @listStr)
END
Both the approaches will delete the jobs, but I want to know which is the best way or you can suggest me more efficient or correct ways to delete the jobs.
And one more question is, do we have to stop/disable the job before deleting it.
TIA Harsha
Upvotes: 7
Views: 11627
Reputation: 3513
I would use approach 1 because it is just simple and effective. There is no need to disable the job before. If you delete a job while it is running, the job will terminate with an error, so check if thats requirement for you.
Way to handle this problem(posted by OP):
IF exists(
select 1 from msdb.dbo.sysjobactivity activity
where activity.run_Requested_date is not null
and activity.stop_execution_date is null
and activity.job_id = @jobId)
exec msdb.dbo.sp_stop_job @job_id = @jobId
I'm not sure if you are worried about the schedule to stay. Depending on how @delete_unused_schedule
is set, sp_delete_job
will delete it by default.
See the stored procedure comment
@delete_unused_schedule BIT = 1 -- For backward compatibility schedules are deleted by default if they are not
-- being used by another job. With the introduction of reusable schedules in V9
-- callers should set this to 0 so the schedule will be preserved for reuse.
So this option will remain you flexible, but i think you will have no need for the schedule because you probably want to clean up your system.
Upvotes: 4