MS SQL server 刪除 工作排程(jobs)時出現錯誤

在SQL server 建立完維護計劃後,若有設定排程,則系統會在排程工作中加入一筆子計劃
通常在刪除 維護計劃時 排程的工作會一併刪除,但有時系統並不會自動刪除關聯的排程
此時若要手動刪除,造成無法刪除sqlagent 裏面的作業,並會出現錯誤訊息 ,表示無法刪除
"子計劃 缷除失敗"
delete 陳述式與reference 條件的約束'FK_subplan_job_id'衝突。衝突發生在資料庫
"msdb",資料表 "dbo.sysmaintplan_subplans",colum "job_id"。



註*過通常會看到這個錯誤訊息都是因為直接刪除子計劃,只要先刪除主計劃就可以了

如果在檢查過後,發現主計劃已經不存在,但子計劃還是無法刪除
此時可以用下列語法來處理
---------------------------------------------------------------------------------------------------------------------------
----處理無法刪除JOB
----可能原因,1.因為維護計劃已被刪除,但子計劃(sysmaintplan_subplans)仍有該計劃之ID
----可能原因,2.因為維護計劃已被刪除,但維護記錄仍有該計劃之ID
---做法,找出sysmaintplan_log裏面有的ID但dbo.sysmaintplan_plans 中沒有的ID,
--刪除sysmaintplan_log不用的ID
---做法,找出sysmaintplan_subplans裏面有的ID但dbo.sysmaintplan_plans 中沒有的ID,
--刪除sysmaintplan_subplans不用的ID
USE msdb ;
GO

-----試著移除JOB
USE msdb ;
GO

EXEC sp_delete_job
    @job_name = '我的計劃' ;
GO

---找出已被刪除的ID
select distinct plan_id  from  dbo.sysmaintplan_log
where plan_id not in(select id from dbo.sysmaintplan_plans )
---刪除該ID的LOG
delete from dbo.sysmaintplan_log
where plan_id not in(select id from dbo.sysmaintplan_plans )
---刪除該sysmaintplan_subplans的plan_id
delete  from dbo.sysmaintplan_subplans 
where plan_id not in(select id from dbo.sysmaintplan_plans )
--再試著刪除job
EXEC sp_delete_job
    @job_name = '我的計劃';
GO


留言

熱門文章