I am trying to create a fairly simple script to work with SQL Server Agent jobs. He performs 2 tasks:
1) If the given task exists, delete it 2) Create a task
(Due to business requirements, I cannot modify an existing task, the script must delete and recreate it.)
Running the script for the first time works fine (creates a task). Starting at any time after this causes error 14274 "Unable to add, update or delete a job created from the MSX server."
I have done a lot for this, and most of the solutions are centered around the server name. My server name has not changed and never was.
Here is what I have:
USE [msdb];
SET NOCOUNT ON;
DECLARE @JobName NVARCHAR(128);
DECLARE @ReturnCode INT;
declare @errCode INT;
SET @JobName = 'AJob';
BEGIN TRANSACTION;
DECLARE @jobId uniqueidentifier;
SET @jobId = (SELECT job_id from msdb.dbo.sysjobs where name = @JobName);
IF(@jobId IS NOT NULL) -- delete if it already exists
begin
EXEC @ReturnCode = msdb.dbo.sp_delete_job @job_id=@jobId
IF(@@ERROR <> 0 OR @ReturnCode <> 0)
begin
set @errCode = @@ERROR;
GOTO QuitWithRollback;
end
print 'deleted job';
end
-- create the job
EXEC @ReturnCode = msdb.dbo.sp_add_job @job_name=@JobName,
@enabled=1,
@notify_level_eventlog=0, -- on failure
@notify_level_email=0,
@notify_level_netsend=0, -- never
@notify_level_page=0,
@delete_level=0,
@description=NULL,
@owner_login_name=N'sa',
@notify_email_operator_name=NULL,
@job_id = @jobId OUTPUT
IF(@@ERROR <> 0 OR @ReturnCode <> 0)
begin
set @errCode = @@ERROR;
GOTO QuitWithRollback;
end
print 'added job';
-- Server
EXEC @ReturnCode = msdb.dbo.sp_add_jobserver
@job_id = @jobId
IF(@@ERROR <> 0 OR @ReturnCode <> 0)
GOTO QuitWithRollback;
COMMIT TRANSACTION;
RETURN;
QuitWithRollback:
IF(@@TRANCOUNT > 0)
ROLLBACK TRANSACTION;
print 'Err: ' + CAST(@errCode AS varchar(10)) + ' ret: ' + cast(@ReturnCode as varchar(10));
I am running it on SQL 2008 SP1. Any help would be greatly appreciated!