Send alert out when SQL Server Restarts

An easy to set up procedure which runs every time SQL Server starts. This can be particular useful in clusters if the instances can move around nodes.

CREATE PROCEDURE [dbo].[spEmailSQLServerRestart]
AS
  BEGIN
-- Declare Variables
DECLARE @strServer VARCHAR(128) = CONVERT(VARCHAR(128), SERVERPROPERTY('ComputerNamePhysicalNetBIOS'))
DECLARE @strMailSubject VARCHAR(128) = 'SQL Server '
+ UPPER(@@SERVERNAME) + ' restarted!'
DECLARE @strMailBody VARCHAR(1000) = 'SQL Server '
+ UPPER(@@SERVERNAME) + ' restarted at '
+ CONVERT(VARCHAR(12), GETDATE(), 108) + ' on '
+ CONVERT(VARCHAR(12), GETDATE(), 103)
+ ' Now running on server: ' + @strServer
-- Wait for the database mail engine to start
WAITFOR DELAY '00:00:15'

DECLARE @sender varchar (50)
SELECT @sender = name from msdb..sysmail_profile where profile_id = 1

-- Send Email
EXEC msdb.dbo.sp_send_dbmail @profile_name = @sender,
@recipients = 'DBAOnCallAlerts@autotrader.co.uk',
@subject = @strMailSubject, @body = @strMailBody,
@body_format = 'HTML';
END

Just deploying the procedure in this scenario is not enough to trigger the alert. We now need to tell SQL Server that it should scan for this procedure every time in starts up. This is known as auto execution in SQL Server and is set by sp_procoption (from SQL Server 2008)

To Set a procedure to run on instance startup, you can run:

-- Sets stored procedure for automatic execution.
sp_procoption    @ProcName = 'spEmailSQLServerRestart',
@OptionName = 'startup',
@OptionValue = 'on'

To see which procedures have the startup option set:

SELECT name, type_desc, create_date, modify_date
FROM sys.procedures
WHERE is_auto_executed = 1

From Microsoft:

Startup procedures must be in the master database and cannot contain INPUT or OUTPUT parameters. Execution of the stored procedures starts when all databases are recovered and the “Recovery is completed” message is logged at startup.

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: