Blog » By Brad Corbin on Brad Corbin
Recovering a deleted SQL Job
A user wanted to recover a SQL job that had been deleted from the agent. We do backups of MSDB, of course, but how would you actually recover the job definition?
Thanks to ServerFault and user squillman, we used the following technique. Restore a copy of MSDB (we used MSDB_old, in this case). Then run the following script:
DECLARE @JobID UNIQUEIDENTIFIER SELECT @JobID = job_id FROM msdb_old.dbo.sysjobs WHERE NAME='My Lost Job' INSERT msdb.dbo.sysjobs SELECT * FROM msdb_old.dbo.sysjobs WHERE job_id=@JobID INSERT msdb.dbo.sysjobsteps SELECT * FROM msdb_old.dbo.sysjobsteps WHERE job_id=@JobID SET IDENTITY_INSERT msdb.dbo.sysjobhistory ON INSERT msdb.dbo.sysjobhistory (instance_id,job_id,step_id,step_name,sql_message_id,sql_severity, [message],run_status,run_date,run_time,run_duration,operator_id_emailed, operator_id_netsent,operator_id_paged,retries_attempted,[server]) SELECT instance_id,job_id,step_id,step_name,sql_message_id,sql_severity, [message],run_status,run_date,run_time,run_duration,operator_id_emailed, operator_id_netsent,operator_id_paged,retries_attempted,[server] FROM msdb_old.dbo.sysjobhistory WHERE job_id=@JobID SET IDENTITY_INSERT msdb.dbo.sysjobhistory OFF INSERT msdb.dbo.sysjobschedules SELECT * FROM msdb_old.dbo.sysjobschedules WHERE job_id=@JobID
Worked like a charm! Thanks, squillman!
Note that you’d have to alter this script some if you were trying to retrieve an old version of a still existing job (because your job_id would conflict).
The last part (lines 25 -27) may fail if you do not have a relevant entry in msdb.sysschedules, just need to get that entry too
SET IDENTITY_INSERT msdb.dbo.sysschedules ON
INSERT INTO msdb.dbo.sysschedules
(
schedule_id, schedule_uid, originating_server_id, name, owner_sid, enabled, freq_type, freq_interval, freq_subday_type, freq_subday_interval, freq_relative_interval, freq_recurrence_factor, active_start_date, active_end_date, active_start_time, active_end_time, date_created, date_modified, version_number
)
SELECT ss.schedule_id, schedule_uid, originating_server_id, name, owner_sid, enabled, freq_type, freq_interval, freq_subday_type, freq_subday_interval, freq_relative_interval, freq_recurrence_factor, active_start_date, active_end_date, active_start_time, active_end_time, date_created, date_modified, version_number
FROM msdb_old.dbo.sysschedules ss
INNER JOIN msdb_old.dbo.sysjobschedules js
ON ss.schedule_id = js.schedule_id
WHERE js.job_id=@JobID
SET IDENTITY_INSERT msdb.dbo.sysschedules OFF