Showing posts with label Maintenance Plan. Show all posts
Showing posts with label Maintenance Plan. Show all posts

Unable to Delete SQL Server Maintenance Plan and SQL Server Agent Job

Problem

I have encountered an error recently when I was doing some test to build a maintenance plan in SSMS. I tried to delete a maintenance plan which I did not need any more, an error showed up:

Exception has been thrown by the target of an invocation. (mscorlib)
Additional information:
Index was out of range. Must be non-negative and less than the size of the collection. Parameter name: index (mscorlib).


When I tried to delete the SQL Server Agent job related to this maintenance plan, this error showed up:

Drop failed for Job "Database Maintenance.Subplan_1". (Microsoft.SqlServer.Smo)
Additional Information:
An exception occurred while executing a Transact-SQL statement or batch.
(Microsoft.SqlServer.ConnectionInfo)
The DELETE statement conflicted with the REFERENCE constraint "FK_subplan_job_id". The conflict occurred in database "msdb", table "dbo.sysmaintplan_subplans", column 'job_id'.
The statement has been terminated. (Microsoft SQL Server, Error: 547)



Solution

We will have to remove the data entries of the jobs and  plans manually from "msdb" system database.
The following is the steps to be taken:

Step 1. find the job_id for the job

use this query to get the job_id:
use msdb
go
select job_id from sysjobs where name = 'yourjobname'

Replace yourjobname with your SQL Server Agent job name shown in SSMS. In my case, it is 'Database Maintenance.Subplan_1'.

Step 2. find the plan_id

use this query to get the plan_id
use msdb
go
select plan_id from dbo.sysmaintplan_subplans
where job_id ='yourjobid'

Replace 'yourjobid' with the job_id obtained from Step 1.

Step 3. delete the data entries of the jobs and plans

Use these queries to delete the records:
use msdb
go
delete from [dbo].[sysjobschedules] where job_id = 'yourjobid'
go
delete from [dbo].[sysmaintplan_log] where plan_id = 'yourplanid'
go
delete from [dbo].[sysmaintplan_subplans] where job_id = 'yourjobid'
go
delete from sysjobs where job_id = 'yourjobid'


Step 4. delete the maintenance plan package

Connect SSMS to Integrated Service.


The expand "Stored Packages" -- "MSDB" --- "Maintenance Plans", right click on the maintenance plan, and select "Delete" from the right click menu.