Sql-server – Monitor SQLAgent

monitoringsql-server-2008-r2sql-server-agent

I detected that SQLAgent was not running on one of our servers due to a unexpected memory leak error that caused SQL Agent to shutdown. There were not alerts configured so one main job that was supposed to be running there was not. Is there a way to monitor SQL Agent from SQL Server itself?

I've done lot of searches but can't find a way to do it. All I've found lot about monitoring jobs, schedules, etc. But not how to monitor if the SQL Agent stops working, does not restart or anything similar that prevents it to run.

PS: I'm planning on asking another question for the memory leak issue

Best Answer

What you can do is to have below script stored on your server or make it as a stored procedure :

use below with sqlcmd

IF EXISTS (  SELECT 1 
           FROM MASTER.dbo.sysprocesses 
           WHERE program_name = N'SQLAgent - Generic Refresher')
BEGIN
   SELECT @@SERVERNAME AS 'InstanceName', 1 AS 'SQLServerAgentRunning'
END 
ELSE 
BEGIN
EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'databaseMail test profile',  --<-- Change HERE !!
    @recipients = 'databaseteam@somecompany.com', --<-- Change HERE !!
    @body = 'Please check the status of SQL Agent. It is not running !',
    @query = 'SELECT @@SERVERNAME AS [InstanceName], 0 AS [SQLServerAgentRunning]',
    @subject = 'SQL Agent is not running',
    @attach_query_result_as_file = 0 ; -- set it to 1 to receive as txt file attachment
END

enter image description here

What you can do to alleviate it :

enter image description here