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
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):
I’m not sure if you are worried about the schedule to stay. Depending on how
@delete_unused_scheduleis set,sp_delete_jobwill delete it by default.See the stored procedure comment
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.