Thursday, March 15, 2018

SQL Agent Jobs without notifications

All of our SQL Agent Jobs should notify someone if a failure occurs.  Below is a query to find all SQL Agent Jobs that are enabled, and do NOT have an email notification.  Quickly dissecting the script below, we are looking for [notify_level_email] NOT IN (1, 2, 3).

1 = When the job succeeds
2 = When the job fails
3 = When the job completes



Now that we have all the jobs in a cursor, we execute the Stored Procedure msdb.dbo.sp_update_job.

we are Passing in @job_id from the cursor.
@notify_level_eventlog=2, logs job failure to the event log
@notify_level_email=2, sends email when job fails
@notify_email_operator_name=N''SQL_SERVER_OPERATOR'''  sets the operator to receive the email.
USE [msdb]
GO

DECLARE @JOBID VARCHAR(4000)
DECLARE @JOBName VARCHAR(4000)
DECLARE @SQL VARCHAR(4000)

DECLARE Cusrsor_JOBID CURSOR
FOR
SELECT job_id, j.[name]
FROM [dbo].[sysjobs] j
LEFT JOIN [dbo].[sysoperators] o ON (j.[notify_email_operator_id] = o.[id])
WHERE j.[enabled] = 1
AND j.[notify_level_email] NOT IN (1, 2, 3)

OPEN Cusrsor_JOBID
FETCH NEXT FROM Cusrsor_JOBID
INTO @JOBID,@JOBName

WHILE @@FETCH_STATUS = 0
BEGIN

--PRINT @JOBID
--PRINT @JOBName

SET @SQL = '
EXEC msdb.dbo.sp_update_job @job_id=N''' + @JOBID + ''',
@notify_level_eventlog=2,
@notify_level_email=2,
@notify_email_operator_name=N''SQL_SERVER_OPERATOR'''

EXEC( @SQL)

FETCH NEXT FROM Cusrsor_JOBID
INTO @JOBID,@JOBName
END
CLOSE Cusrsor_JOBID;
DEALLOCATE Cusrsor_JOBID;

No comments:

Post a Comment