
/* Update blocked process threshold */
exec master.dbo.sp_configure 'show advanced option', 1;
RECONFIGURE WITH OVERRIDE
EXEC sp_configure 'blocked process threshold', 10 ---- CHANGE HERE !!
exec master.dbo.sp_configure 'show advanced option', 0;
RECONFIGURE WITH OVERRIDE
GO

/* Add table to store alert report*/
USE [HCITools]
GO

IF NOT EXISTS (   SELECT *
                    FROM sys.objects
                   WHERE object_id = OBJECT_ID(N'[dbo].[BlockingSessionInfo]')
                     AND type in ( N'U' ))
BEGIN

    CREATE TABLE [dbo].[BlockingSessionInfo] (
        [SessionInfoId] [int] IDENTITY(1, 1) NOT NULL,
        [AlertTime] [datetime2](0) NOT NULL,
        [BlockingDetails] [xml] NULL,
        [MailNotification] [BIT] NOT NULL
            DEFAULT 0,
        CONSTRAINT [PK_BlockingSessionInfo]
            PRIMARY KEY CLUSTERED ([SessionInfoId] ASC)) ON [PRIMARY]

END
GO

USE [msdb]
GO

/* Deploy job for alert response */

/* Drop existing standard schedule for job */
declare @schedule_id int
declare c_schedules cursor local forward_only static for
    select ss.schedule_id
      from msdb.dbo.sysjobschedules sjs
INNER JOIN msdb.dbo.sysschedules ss
        ON sjs.schedule_id = ss.schedule_id
       AND ss.name NOT LIKE '%#SPEC#'
INNER JOIN msdb.dbo.sysjobs sj
        ON sjs.job_id = sj.job_id
     WHERE sj.name = N'_92050 - Response - Blocked Process Event'

open c_schedules

FETCH NEXT FROM c_schedules into @schedule_id
while @@fetch_status = 0
begin
  IF ((select COUNT(*) from msdb.dbo.sysjobschedules where schedule_id=@schedule_id) = 1)
    EXEC msdb.dbo.sp_delete_schedule @schedule_id=@schedule_id, @force_delete = 1
FETCH NEXT FROM c_schedules into @schedule_id
end

close c_schedules

deallocate c_schedules

IF  EXISTS (SELECT job_id FROM msdb.dbo.sysjobs_view WHERE name = N'_92050 - Response - Blocked Process Event')
EXEC msdb.dbo.sp_delete_job @job_name = N'_92050 - Response - Blocked Process Event', @delete_unused_schedule=0
GO

/* Creation Job and Steps*/
BEGIN TRANSACTION
DECLARE @ReturnCode INT
SELECT @ReturnCode = 0

IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N'DBA-Monitoring' AND category_class=1)
BEGIN
EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N'JOB', @type=N'LOCAL', @name=N'DBA-Monitoring'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

END

/* Add Job */
DECLARE @jobId BINARY(16)
EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N'_92050 - Response - Blocked Process Event', 
		@enabled=1, 
		@notify_level_eventlog=0, 
		@notify_level_email=0, 
		@notify_level_netsend=0, 
		@notify_level_page=0, 
		@delete_level=0, 
		@description=N'16.11.2018 : RTC Store Blocking session report details and send notification to DBA only every 2 minutes and during opening hours.', 
		@category_name=N'DBA-Monitoring', 
		@start_step_id=1, 
		@owner_login_name=N'sa', @job_id = @jobId OUTPUT
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

/* Add Step */
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Empty step', 
		@step_id=1, 
		@cmdexec_success_code=0, 
		@on_success_action=3, 
		@on_success_step_id=0, 
		@on_fail_action=3, 
		@on_fail_step_id=0, 
		@retry_attempts=0, 
		@retry_interval=0, 
		@os_run_priority=0, @subsystem=N'TSQL', 
		@command=N'/* Empty step */', 
		@database_name=N'master', 
		@output_file_name=NULL, 
		@flags=0, 
		@database_user_name=NULL, 
		@server=NULL, 
		@additional_parameters=NULL, 
		@proxy_id=NULL, 
		@proxy_name=NULL
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/* Add Step */
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Insert Blocking info', 
		@step_id=2, 
		@cmdexec_success_code=0, 
		@on_success_action=3, 
		@on_success_step_id=0, 
		@on_fail_action=4, 
		@on_fail_step_id=5, 
		@retry_attempts=0, 
		@retry_interval=0, 
		@os_run_priority=0, @subsystem=N'TSQL', 
		@command=N'INSERT INTO dbo.BlockingSessionInfo (

AlertTime,

BlockingDetails

)

VALUES (

GETDATE(),

''$(ESCAPE_NONE(WMI(TextData)))''

)', 
		@database_name=N'HCITools', 
		@output_file_name=NULL, 
		@flags=0, 
		@database_user_name=NULL, 
		@server=NULL, 
		@additional_parameters=NULL, 
		@proxy_id=NULL, 
		@proxy_name=NULL
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/* Add Step */
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Send blocking session report if needed', 
		@step_id=3, 
		@cmdexec_success_code=0, 
		@on_success_action=3, 
		@on_success_step_id=0, 
		@on_fail_action=4, 
		@on_fail_step_id=5, 
		@retry_attempts=0, 
		@retry_interval=0, 
		@os_run_priority=0, @subsystem=N'TSQL', 
		@command=N'DECLARE @reportXml XML;
DECLARE @XmlToString NVARCHAR(MAX);
DECLARE @path NVARCHAR(4000);

SET @reportXml = CONVERT(XML, N''$(ESCAPE_SQUOTE(WMI(TextData)))'', 1);

SET @XmlToString = CONVERT(NVARCHAR(MAX), @reportXml);

/* Elapse time since last mail sent in seconds*/
DECLARE @elapseTime AS INT;
SELECT @elapseTime = 0;
SELECT TOP 1
       @elapseTime = DATEDIFF(SECOND, AlertTime, GETDATE())
FROM HCITools.dbo.BlockingSessionInfo
WHERE MailNotification = 1
ORDER BY AlertTime DESC;

IF EXISTS (SELECT 1 FROM sys.databases WHERE name = ''Arizona'')
BEGIN
    IF (Arizona.dbo.aps_fn_Is_working_hour(GETDATE(), NULL, NULL) = 1)
       AND
       (
           @elapseTime >= 120
           OR NOT EXISTS
    (
        SELECT 1
        FROM HCITools.dbo.BlockingSessionInfo
        WHERE MailNotification = 1
    )
       )
    BEGIN
        EXEC [Arizona].[dbo].[aps_Send_Mail_with_template] @in_param_varchar_2 = ''DBA_operator'',
                                                           -- ,@in_param_varchar_3  =@XmlToString -- ''A session blocked has occured in SQL Server. Attached you will find the lock graph.''
                                                           @in_param_message = @XmlToString,
                                                           @in_job_type = 3;

        UPDATE TOP (1)
            HCITools.dbo.BlockingSessionInfo
        SET MailNotification = 1
        WHERE SessionInfoId IN
              (
                  SELECT TOP 1
                         SessionInfoId
                  FROM HCITools.dbo.BlockingSessionInfo
                  ORDER BY AlertTime DESC
              );
    END;
END;
;

', 
		@database_name=N'master', 
		@output_file_name=NULL, 
		@flags=0, 
		@database_user_name=NULL, 
		@server=NULL, 
		@additional_parameters=NULL, 
		@proxy_id=NULL, 
		@proxy_name=NULL
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/* Add Step */
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Empty step for success', 
		@step_id=4, 
		@cmdexec_success_code=0, 
		@on_success_action=1, 
		@on_success_step_id=0, 
		@on_fail_action=2, 
		@on_fail_step_id=0, 
		@retry_attempts=0, 
		@retry_interval=0, 
		@os_run_priority=0, @subsystem=N'TSQL', 
		@command=N'/* Empty step */', 
		@database_name=N'master', 
		@output_file_name=NULL, 
		@flags=0, 
		@database_user_name=NULL, 
		@server=NULL, 
		@additional_parameters=NULL, 
		@proxy_id=NULL, 
		@proxy_name=NULL
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
/* Add Step */
EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N'Send email KO', 
		@step_id=5, 
		@cmdexec_success_code=0, 
		@on_success_action=2, 
		@on_success_step_id=0, 
		@on_fail_action=2, 
		@on_fail_step_id=0, 
		@retry_attempts=0, 
		@retry_interval=0, 
		@os_run_priority=0, @subsystem=N'TSQL', 
		@command=N'exec Get_Job_Error_Info @in_JobName = ''_92050 - Response - Blocked Process Event'', @in_Recipients = ''DBA_operator''', 
		@database_name=N'HCITools', 
		@output_file_name=NULL, 
		@flags=0, 
		@database_user_name=NULL, 
		@server=NULL, 
		@additional_parameters=NULL, 
		@proxy_id=NULL, 
		@proxy_name=NULL
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback

/* Attach existing specific schedule for job */
declare @enabled_schedule int,
        @schedule_name nvarchar(50)
declare c_schedules cursor local forward_only static for
select enabled, name
  from msdb.dbo.sysschedules
 where name LIKE '_92050%'
   and name LIKE '%#SPEC#'

open c_schedules

FETCH NEXT FROM c_schedules into @enabled_schedule, @schedule_name
while @@fetch_status = 0
begin
  EXEC @ReturnCode = msdb.dbo.sp_attach_schedule @job_id = @jobId, @schedule_name=@schedule_name
  IF(@enabled_schedule = 1)
  begin
    SET @schedule_name = SUBSTRING(@schedule_name,0,LEN(@schedule_name)-5)
    IF EXISTS (select name from msdb.dbo.sysschedules where name = @schedule_name)
      EXEC @ReturnCode = msdb.dbo.sp_update_schedule @name=@schedule_name, @enabled=0
  end
  IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
FETCH NEXT FROM c_schedules into @enabled_schedule, @schedule_name
end

close c_schedules

deallocate c_schedules

EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N'(local)'
IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
COMMIT TRANSACTION
GOTO EndSave
QuitWithRollback:
    IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
EndSave:

GO

/* Add categorie for SQL Server Agent Alerts */
DECLARE @CategoryName sysname,
        @AlertName    sysname
   
SET @CategoryName = N'SQL Server Agent Alerts';

IF NOT EXISTS (SELECT *
                 FROM msdb.dbo.syscategories
                WHERE category_class = 2  /*2=Alert*/
                  AND category_type = 3
                  AND name = @CategoryName)
BEGIN
    PRINT 'Add Category SQL Server Agent Alerts'
    EXEC dbo.sp_add_category @class = N'ALERT', @type = N'NONE', @name = @CategoryName; 
END 

/****** Alert [DBA - WMI:Respond to Blocking session]   ******/
SET @AlertName = 'DBA - WMI:Respond to Blocking session'
IF  EXISTS (SELECT name FROM msdb.dbo.sysalerts WHERE name = @AlertName)
EXEC msdb.dbo.sp_delete_alert @name= @AlertName
GO

DECLARE @CategoryName sysname,
        @AlertName    sysname

SET @CategoryName = N'SQL Server Agent Alerts';
SET @AlertName = 'DBA - WMI:Respond to Blocking session'
DECLARE @namespace NVARCHAR(200);
IF (SERVERPROPERTY('InstanceName') IS NOT NULL)
BEGIN
   SELECT @namespace = N'\\.\root\Microsoft\SqlServer\ServerEvents\'
                       + CONVERT(NVARCHAR(128), SERVERPROPERTY('InstanceName'));
END;
ELSE
BEGIN
   DECLARE @InstanceName SYSNAME
   SET @InstanceName = CONVERT(VARCHAR(128),ISNULL(SERVERPROPERTY ('InstanceName'),'MSSQLSERVER'))
   
   SELECT @namespace = N'\\.\root\Microsoft\SqlServer\ServerEvents\' + @InstanceName;
END;

    EXEC msdb.dbo.sp_add_alert @name = @AlertName, 
		@message_id=0, 
		@severity=0, 
		@enabled=1, 
		@delay_between_responses=10, 
		@include_event_description_in=5, 
		@category_name=@CategoryName, 
		@wmi_namespace=@namespace, 
		@wmi_query=N'SELECT * FROM BLOCKED_PROCESS_REPORT', 
		@job_name=N'_92050 - Response - Blocked Process Event'
GO


