Thursday, October 1, 2015

Notify when SQL SERVER and Agent Restarts (works for both)

-- Alert on SQL Server Agent and/or SQL Server service restarts
-- Replace your recipients in line # 14

-- declare the required variables
DECLARE @Message VARCHAR(MAX)
, @Subject VARCHAR(123)
, @Recipients VARCHAR(123)
, @IsDBMailEnabled BIT
, @MailProfile VARCHAR(123)
, @IsClustered VARCHAR(1) -- this is because SERVERPROPERTY('IsClustered') is a sql_variant data type
, @CurrentNodeName VARCHAR(123)
, @InstanceName VARCHAR(123)
, @RestartTime VARCHAR(123)

set @Recipients = 'naresh.koudagani@xyz.com' -- specify the recipients here, separate with ;

SELECT @InstanceName = CONVERT(VARCHAR, SERVERPROPERTY('ServerName'))
, @IsClustered = CONVERT (VARCHAR, SERVERPROPERTY('IsClustered'))
, @CurrentNodeName = CONVERT (VARCHAR, SERVERPROPERTY('ComputerNamePhysicalNetBIOS'))

-- SQL Server service has been restarted
IF (
SELECT DATEDIFF(MI, CREATE_DATE,GETDATE() )
FROM SYS.DATABASES
WHERE NAME = 'TEMPDB'
) <= 3 -- SQL Server service restarted in the past 3 minutes
BEGIN
SELECT @RestartTime = CONVERT(VARCHAR, create_date, 13)
FROM SYS.databases
WHERE NAME = 'TEMPDB'

SET @Message = @InstanceName + ' SQL Server Agent service and SQL Server service have been restarted at: ' +@RestartTime
SET @Subject = @InstanceName + ' SQL Server Agent service and SQL Server service have been restarted!'


IF @IsClustered = '1'
BEGIN
SET @Message = @Message + ' and the current active node is: ' +@CurrentNodeName+ '.'
SET @Subject = @Subject + ' The current active node is: ' +@CurrentNodeName+ '.'
END
END
ELSE
BEGIN
SET @Message = @InstanceName + ' SQL Server Agent service has been restarted!'
SET @Subject = @InstanceName + ' SQL Server Agent service restarted!'
END

SET @Message = @Message + CHAR(10)
SET @Message = @Message + 'If this is not a planned maintenace. Please verify the status of the databases before restarting any application services and review the log files to find the possible root causes!'

-- Find the database mail profile name
create table #dbmail_profile
(
profileid int null,
profilename varchar(125) null,
accountid int null,
accountname varchar(125) null,
sequencenumber int null
)
insert #dbmail_profile
EXECUTE msdb.dbo.sysmail_help_profileaccount_sp;

select @MailProfile = profilename
from #dbmail_profile
where sequencenumber = 1

drop table #dbmail_profile

EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'DBMAIL',
@recipients = @Recipients,
@subject = @Subject,
@body_format = 'TEXT',
@body = @Message;

No comments:

Post a Comment

https://blog.sqlauthority.com/2009/06/27/sql-server-fix-error-17892-logon-failed-for-login-due-to-trigger-execution-changed-database-context...