How to Send an Email Notification When SQL Server Service Restarts

Monitoring SQL Server service restarts is essential for maintaining database availability and troubleshooting unexpected issues. In this post, I’ll show you how to automate email notifications whenever SQL Server services start.

Why Monitor Service Restarts?

Unexpected SQL Server service restarts could indicate issues like:

  • Server reboots
  • Maintenance activities
  • Resource constraints
  • Crashes or failures

Getting an instant email notification helps database administrators (DBAs) quickly investigate the reason for the restart.

SQL Script to Send Email on Service Restart

Below is a simple T-SQL script that sends an email when SQL Server services restart.

USE msdb

GO

-- Declare variables for email content

DECLARE @ServerName VARCHAR(128),

        @ComputerNamePhysicalNetBIOS VARCHAR(128),

        @Datetime DATETIME,

        @EmailRecipients VARCHAR(512),

        @EmailSubject VARCHAR(128),

        @MessageBody VARCHAR(512)

-- Assign values to variables

SELECT @ComputerNamePhysicalNetBIOS = CAST(SERVERPROPERTY('ComputerNamePhysicalNetBIOS') AS VARCHAR(128)),

       @ServerName = CAST(SERVERPROPERTY('ServerName') AS VARCHAR(128)),

       @Datetime = GETDATE(),

       @EmailRecipients = 'bajeyudu@sqldbanow.com', -- Add multiple emails using a semicolon (;)

       @EmailSubject = SQL Server Services Have Been Started!!!'

-- Construct the email body

SELECT @MessageBody = 'SQL Server services have been started on a SQL Server Instance named ' + @ServerName + CHAR(13) +

                      'running on Windows server ' + @ComputerNamePhysicalNetBIOS + '.' + CHAR(13) + CHAR(13) +

                      'Investigate the service restart if it has not been communicated.'

-- Send email using Database Mail

EXEC sp_send_dbmail

    @recipients = @EmailRecipients,

    @subject = @EmailSubject,

    @body = @MessageBody,

    @body_format = 'TEXT'

How to Automate This?

  1. Enable Database Mail:
    Ensure Database Mail is configured in SQL Server. 

  1. Create a SQL Server Agent Job:
    • Open SQL Server AgentJobsNew Job.
    • Set the job name (e.g., "Monitor SQL Service Restarts").
    • Add a new step and paste the above script.
    • Schedule it to run at server startup (under Schedules, choose Start automatically when SQL Server Agent starts)

No comments:

Post a Comment