Create a trigger on SQL Agent job status change.

nn

USE [msdb]
GO
/*
Create a trigger to send a notification on a status change

*/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

Create TRIGGER [dbo].[sqlagentjobstatuschange]
ON [dbo].[sysjobs]
FOR UPDATE AS

SET NOCOUNT ON;

–** Declare variables
DECLARE @username VARCHAR(50),
@hostName VARCHAR(50),
@jobName VARCHAR(100),
@newEnabled INT,
@oldEnabled INT,
@jobCreated INT,
@bodyText VARCHAR(200),
@subjectText VARCHAR(200),
@servername VARCHAR(50),
@profileName VARCHAR(50) = ‘Add Profile’,
@recipients VARCHAR(500) = ‘Add email Address’

–** Set Variables

SELECT @username = SYSTEM_USER
SELECT @hostName = HOST_NAME()
SELECT @servername = @@servername
SELECT @newEnabled = ENABLED FROM Inserted
SELECT @oldEnabled = ENABLED FROM Deleted
SELECT @jobName = Name FROM Inserted

–** Check if the job was enabled or disabled

IF @newEnabled <> @oldEnabled
BEGIN

IF @newEnabled = 1
BEGIN
SET @bodyText = ‘The user (‘ + @username + ‘) enabled the job from ‘ + @hostName + ‘ on ‘ + CONVERT(VARCHAR(20),GETDATE(),100) + ‘.’
SET @subjectText = @servername + ‘ : [‘ + @jobName + ‘] has been ENABLED’
END

IF @newEnabled = 0
BEGIN
SET @bodyText = ‘The user (‘ + @username + ‘) disabled the job from ‘ + @hostName + ‘ on ‘ + CONVERT(VARCHAR(20),GETDATE(),100) + ‘.’
SET @subjectText = @servername+’ : [‘ + @jobName + ‘] has been DISABLED’
END

SET @subjectText = ‘SQL Job on ‘ + @subjectText

–** Any change detected send a notification out

EXEC msdb.dbo.sp_send_dbmail
@profile_name = @profileName,
@recipients = @recipients,
@body = @bodyText,
@subject = @subjectText;

END;


Discover more from SQLYARD

Subscribe to get the latest posts sent to your email.

Leave a Reply

Discover more from SQLYARD

Subscribe now to keep reading and get access to the full archive.

Continue reading