Search

Thursday, April 11, 2013

Identify orphaned (no longer targeted to a database) SQL Server Agent jobs after dropping a database

When a database is dropped, the jobs remain active in the SQL Server Agent and if a schedule is associated to the job, failures would be reported whenever the jobs are automatically executed. As part of the standard process that I follow whenever I drop a database, I run the following script to identify SQL Server Agent jobs which are no longer targeted to any database.

USE msdb;
GO

--Query to identify orphaned jobs!
SELECT sj.database_name AS OriginalTargetDBName,      
sj.job_id AS JobId,       
sj.step_id AS JobStepId,       
sj.step_name AS StepName,      
sj.subsystem AS SubSystem,       
sj.command AS JobStepCommand,       
sj.last_run_date AS LastExecutionDate
FROM msdb.dbo.sysjobsteps AS sj
WHERE DB_ID(sj.database_name) IS NULL AND   --If the database no longer exists,                                         
--DB_ID() would return NULL  
sj.database_name IS NOT NULL
GO


No comments:

Post a Comment