-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMonitora e envia email.sql
511 lines (451 loc) · 26.1 KB
/
Monitora e envia email.sql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
-- Escolha a base de dados para criar o Script
USE BancoDados
/*
Instrução de utilização:
-- Alterar para o profile do seu servidor:
@profile_name = 'MSSQLServer',
--Alterar para o e-mail que você quer enviar o alerta
@recipients = '[email protected]',
*/
GO
/*******************************************************************************************************************************
-- Tabela de controle que será utilizada para armazenar o Historico dos Alertas.
*******************************************************************************************************************************/
CREATE TABLE [dbo].[Alerta] (
[Id_Alerta] INT IDENTITY PRIMARY KEY,
[Nm_Alerta] VARCHAR(200),
[Ds_Mensagem] VARCHAR(2000),
[Fl_Tipo] TINYINT, -- 0: CLEAR / 1: ALERTA
[Dt_Alerta] DATETIME DEFAULT(GETDATE())
)
GO
/*******************************************************************************************************************************
-- ALERTA: PROCESSO BLOQUEADO
*******************************************************************************************************************************/
CREATE PROCEDURE [dbo].[stpAlerta_Processo_Bloqueado]
AS
BEGIN
SET NOCOUNT ON
-- Declara as variaveis
DECLARE @Subject VARCHAR(500), @Fl_Tipo TINYINT, @Qtd_Segundos INT, @Consulta VARCHAR(8000), @Importance AS VARCHAR(6), @Dt_Atual DATETIME,
@EmailBody VARCHAR(MAX), @AlertaLockHeader VARCHAR(MAX), @AlertaLockTable VARCHAR(MAX), @EmptyBodyEmail VARCHAR(MAX),
@AlertaLockRaizHeader VARCHAR(MAX), @AlertaLockRaizTable VARCHAR(MAX), @Qt_Tempo_Lock INT, @Qt_Tempo_Raiz_Lock INT
-- Quantidade em Minutos
SELECT @Qt_Tempo_Lock = 2, -- Query que esta sendo bloqueada (rodando a mais de 2 minutos)
@Qt_Tempo_Raiz_Lock = 1 -- Query que esta gerando o lock (rodando a mais de 1 minuto)
--------------------------------------------------------------------------------------------------------------------------------
-- Cria Tabela para armazenar os Dados da SP_WHOISACTIVE
--------------------------------------------------------------------------------------------------------------------------------
-- Cria a tabela que ira armazenar os dados dos processos
IF ( OBJECT_ID('tempdb..#Resultado_WhoisActive') IS NOT NULL )
DROP TABLE #Resultado_WhoisActive
CREATE TABLE #Resultado_WhoisActive (
[dd hh:mm:ss.mss] VARCHAR(20),
[database_name] NVARCHAR(128),
[login_name] NVARCHAR(128),
[host_name] NVARCHAR(128),
[start_time] DATETIME,
[status] VARCHAR(30),
[session_id] INT,
[blocking_session_id] INT,
[wait_info] VARCHAR(MAX),
[open_tran_count] INT,
[CPU] VARCHAR(MAX),
[reads] VARCHAR(MAX),
[writes] VARCHAR(MAX),
[sql_command] XML
)
-- Seta a hora atual
SELECT @Dt_Atual = GETDATE()
--------------------------------------------------------------------------------------------------------------------------------
-- Carrega os Dados da SP_WHOISACTIVE
--------------------------------------------------------------------------------------------------------------------------------
-- Retorna todos os processos que estão sendo executados no momento
EXEC [dbo].[sp_WhoIsActive]
@get_outer_command = 1,
@output_column_list = '[dd hh:mm:ss.mss][database_name][login_name][host_name][start_time][status][session_id][blocking_session_id][wait_info][open_tran_count][CPU][reads][writes][sql_command]',
@destination_table = '#Resultado_WhoisActive'
-- Altera a coluna que possui o comando SQL
ALTER TABLE #Resultado_WhoisActive
ALTER COLUMN [sql_command] VARCHAR(MAX)
UPDATE #Resultado_WhoisActive
SET [sql_command] = REPLACE( REPLACE( REPLACE( REPLACE( CAST([sql_command] AS VARCHAR(1000)), '<?query --', ''), '--?>', ''), '>', '>'), '<', '')
-- select * from #Resultado_WhoisActive
-- Verifica se não existe nenhum processo em Execução
IF NOT EXISTS ( SELECT TOP 1 * FROM #Resultado_WhoisActive )
BEGIN
INSERT INTO #Resultado_WhoisActive
SELECT NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL,NULL
END
-- Verifica o último Tipo do Alerta registrado -> 0: CLEAR / 1: ALERTA
SELECT @Fl_Tipo = [Fl_Tipo]
FROM [dbo].[Alerta]
WHERE [Id_Alerta] = (SELECT MAX(Id_Alerta) FROM [dbo].[Alerta] WHERE [Nm_Alerta] = 'Processo Bloqueado' )
/*******************************************************************************************************************************
-- Verifica se existe algum Processo Bloqueado
*******************************************************************************************************************************/
IF EXISTS (
SELECT NULL
FROM #Resultado_WhoisActive A
JOIN #Resultado_WhoisActive B ON A.[blocking_session_id] = B.[session_id]
WHERE DATEDIFF(SECOND,A.[start_time], @Dt_Atual) > @Qt_Tempo_Lock * 60 -- A query que está sendo bloqueada está rodando a mais 2 minutos
AND DATEDIFF(SECOND,B.[start_time], @Dt_Atual) > @Qt_Tempo_Raiz_Lock * 60 -- A query que está bloqueando está rodando a mais de 1 minuto
)
BEGIN -- INICIO - ALERTA
IF ISNULL(@Fl_Tipo, 0) = 0 -- Envia o Alerta apenas uma vez
BEGIN
--------------------------------------------------------------------------------------------------------------------------------
-- Verifica a quantidade de processos bloqueados
--------------------------------------------------------------------------------------------------------------------------------
-- Declara a variavel e retorna a quantidade de Queries Lentas
DECLARE @QtdProcessosBloqueados INT = (
SELECT COUNT(*)
FROM #Resultado_WhoisActive A
JOIN #Resultado_WhoisActive B ON A.[blocking_session_id] = B.[session_id]
WHERE DATEDIFF(SECOND,A.[start_time], @Dt_Atual) > @Qt_Tempo_Lock * 60
AND DATEDIFF(SECOND,B.[start_time], @Dt_Atual) > @Qt_Tempo_Raiz_Lock * 60
)
DECLARE @QtdProcessosBloqueadosLocks INT = (
SELECT COUNT(*)
FROM #Resultado_WhoisActive A
WHERE [blocking_session_id] IS NOT NULL
)
--------------------------------------------------------------------------------------------------------------------------------
-- Verifica o Nivel dos Locks
--------------------------------------------------------------------------------------------------------------------------------
ALTER TABLE #Resultado_WhoisActive
ADD Nr_Nivel_Lock TINYINT
-- Nivel 0
UPDATE A
SET Nr_Nivel_Lock = 0
FROM #Resultado_WhoisActive A
WHERE blocking_session_id IS NULL AND session_id IN ( SELECT DISTINCT blocking_session_id
FROM #Resultado_WhoisActive WHERE blocking_session_id IS NOT NULL)
UPDATE A
SET Nr_Nivel_Lock = 1
FROM #Resultado_WhoisActive A
WHERE Nr_Nivel_Lock IS NULL
AND blocking_session_id IN ( SELECT DISTINCT session_id FROM #Resultado_WhoisActive WHERE Nr_Nivel_Lock = 0)
UPDATE A
SET Nr_Nivel_Lock = 2
FROM #Resultado_WhoisActive A
WHERE Nr_Nivel_Lock IS NULL
AND blocking_session_id IN ( SELECT DISTINCT session_id FROM #Resultado_WhoisActive WHERE Nr_Nivel_Lock = 1)
UPDATE A
SET Nr_Nivel_Lock = 3
FROM #Resultado_WhoisActive A
WHERE Nr_Nivel_Lock IS NULL
AND blocking_session_id IN ( SELECT DISTINCT session_id FROM #Resultado_WhoisActive WHERE Nr_Nivel_Lock = 2)
-- Tratamento quando não tem um Lock Raiz
IF NOT EXISTS(select * from #Resultado_WhoisActive where Nr_Nivel_Lock IS NOT NULL)
BEGIN
UPDATE A
SET Nr_Nivel_Lock = 0
FROM #Resultado_WhoisActive A
WHERE session_id IN ( SELECT DISTINCT blocking_session_id
FROM #Resultado_WhoisActive WHERE blocking_session_id IS NOT NULL)
UPDATE A
SET Nr_Nivel_Lock = 1
FROM #Resultado_WhoisActive A
WHERE Nr_Nivel_Lock IS NULL
AND blocking_session_id IN ( SELECT DISTINCT session_id FROM #Resultado_WhoisActive WHERE Nr_Nivel_Lock = 0)
UPDATE A
SET Nr_Nivel_Lock = 2
FROM #Resultado_WhoisActive A
WHERE Nr_Nivel_Lock IS NULL
AND blocking_session_id IN ( SELECT DISTINCT session_id FROM #Resultado_WhoisActive WHERE Nr_Nivel_Lock = 1)
UPDATE A
SET Nr_Nivel_Lock = 3
FROM #Resultado_WhoisActive A
WHERE Nr_Nivel_Lock IS NULL
AND blocking_session_id IN ( SELECT DISTINCT session_id FROM #Resultado_WhoisActive WHERE Nr_Nivel_Lock = 2)
END
/*******************************************************************************************************************************
-- CRIA O EMAIL - ALERTA
*******************************************************************************************************************************/
--------------------------------------------------------------------------------------------------------------------------------
-- ALERTA - HEADER - RAIZ LOCK
--------------------------------------------------------------------------------------------------------------------------------
SET @AlertaLockRaizHeader = '<font color=black bold=true size=5>'
SET @AlertaLockRaizHeader = @AlertaLockRaizHeader + '<BR /> TOP 50 - Processos Raiz Lock <BR />'
SET @AlertaLockRaizHeader = @AlertaLockRaizHeader + '</font>'
--------------------------------------------------------------------------------------------------------------------------------
-- ALERTA - BODY - RAIZ LOCK
--------------------------------------------------------------------------------------------------------------------------------
SET @AlertaLockRaizTable = CAST( (
SELECT td = [Nr_Nivel_Lock] + '</td>'
+ '<td>' + [Duração] + '</td>'
+ '<td>' + [database_name] + '</td>'
+ '<td>' + [login_name] + '</td>'
+ '<td>' + [host_name] + '</td>'
+ '<td>' + [start_time] + '</td>'
+ '<td>' + [status] + '</td>'
+ '<td>' + [session_id] + '</td>'
+ '<td>' + [blocking_session_id] + '</td>'
+ '<td>' + [Wait] + '</td>'
+ '<td>' + [open_tran_count] + '</td>'
+ '<td>' + [CPU] + '</td>'
+ '<td>' + [reads] + '</td>'
+ '<td>' + [writes] + '</td>'
+ '<td>' + [sql_command] + '</td>'
FROM (
-- Dados da Tabela do EMAIL
SELECT TOP 50
CAST(Nr_Nivel_Lock AS VARCHAR) AS [Nr_Nivel_Lock],
ISNULL([dd hh:mm:ss.mss], '-') AS [Duração],
ISNULL([database_name], '-') AS [database_name],
ISNULL([login_name], '-') AS [login_name],
ISNULL([host_name], '-') AS [host_name],
ISNULL(CONVERT(VARCHAR(20), [start_time], 120), '-') AS [start_time],
ISNULL([status], '-') AS [status],
ISNULL(CAST([session_id] AS VARCHAR), '-') AS [session_id],
ISNULL(CAST([blocking_session_id] AS VARCHAR), '-') AS [blocking_session_id],
ISNULL([wait_info], '-') AS [Wait],
ISNULL(CAST([open_tran_count] AS VARCHAR), '-') AS [open_tran_count],
ISNULL([CPU], '-') AS [CPU],
ISNULL([reads], '-') AS [reads],
ISNULL([writes], '-') AS [writes],
ISNULL(SUBSTRING([sql_command], 1, 300), '-') AS [sql_command]
FROM #Resultado_WhoisActive
WHERE Nr_Nivel_Lock IS NOT NULL
ORDER BY [Nr_Nivel_Lock], [start_time]
) AS D ORDER BY [Nr_Nivel_Lock], [start_time]
FOR XML PATH( 'tr' ), TYPE) AS VARCHAR(MAX)
)
-- Corrige a Formatação da Tabela
SET @AlertaLockRaizTable = REPLACE( REPLACE( REPLACE( @AlertaLockRaizTable, '<', '<'), '>', '>'), '<td>', '<td align = center>')
-- Títulos da Tabela do EMAIL
SET @AlertaLockRaizTable =
'<table cellspacing="2" cellpadding="5" border="3">'
+ '<tr>
<th bgcolor=#0B0B61 width="80"><font color=white>Nivel Lock</font></th>
<th bgcolor=#0B0B61 width="140"><font color=white>[dd hh:mm:ss.mss]</font></th>
<th bgcolor=#0B0B61 width="100"><font color=white>Database</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Login</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Host Name</font></th>
<th bgcolor=#0B0B61 width="200"><font color=white>Hora Início</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Status</font></th>
<th bgcolor=#0B0B61 width="30"><font color=white>ID Sessão</font></th>
<th bgcolor=#0B0B61 width="60"><font color=white>ID Sessão Bloqueando</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Wait</font></th>
<th bgcolor=#0B0B61 width="60"><font color=white>Transações Abertas</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>CPU</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Reads</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Writes</font></th>
<th bgcolor=#0B0B61 width="300"><font color=white>Query</font></th>
</tr>'
+ REPLACE( REPLACE( @AlertaLockRaizTable, '<', '<'), '>', '>')
+ '</table>'
--------------------------------------------------------------------------------------------------------------------------------
-- ALERTA - HEADER
--------------------------------------------------------------------------------------------------------------------------------
SET @AlertaLockHeader = '<font color=black bold=true size=5>'
SET @AlertaLockHeader = @AlertaLockHeader + '<BR /> TOP 50 - Processos executando no Banco de Dados <BR />'
SET @AlertaLockHeader = @AlertaLockHeader + '</font>'
--------------------------------------------------------------------------------------------------------------------------------
-- ALERTA - BODY
--------------------------------------------------------------------------------------------------------------------------------
SET @AlertaLockTable = CAST( (
SELECT td = [Duração] + '</td>'
+ '<td>' + [database_name] + '</td>'
+ '<td>' + [login_name] + '</td>'
+ '<td>' + [host_name] + '</td>'
+ '<td>' + [start_time] + '</td>'
+ '<td>' + [status] + '</td>'
+ '<td>' + [session_id] + '</td>'
+ '<td>' + [blocking_session_id] + '</td>'
+ '<td>' + [Wait] + '</td>'
+ '<td>' + [open_tran_count] + '</td>'
+ '<td>' + [CPU] + '</td>'
+ '<td>' + [reads] + '</td>'
+ '<td>' + [writes] + '</td>'
+ '<td>' + [sql_command] + '</td>'
FROM (
-- Dados da Tabela do EMAIL
SELECT TOP 50
ISNULL([dd hh:mm:ss.mss], '-') AS [Duração],
ISNULL([database_name], '-') AS [database_name],
ISNULL([login_name], '-') AS [login_name],
ISNULL([host_name], '-') AS [host_name],
ISNULL(CONVERT(VARCHAR(20), [start_time], 120), '-') AS [start_time],
ISNULL([status], '-') AS [status],
ISNULL(CAST([session_id] AS VARCHAR), '-') AS [session_id],
ISNULL(CAST([blocking_session_id] AS VARCHAR), '-') AS [blocking_session_id],
ISNULL([wait_info], '-') AS [Wait],
ISNULL(CAST([open_tran_count] AS VARCHAR), '-') AS [open_tran_count],
ISNULL([CPU], '-') AS [CPU],
ISNULL([reads], '-') AS [reads],
ISNULL([writes], '-') AS [writes],
ISNULL(SUBSTRING([sql_command], 1, 300), '-') AS [sql_command]
FROM #Resultado_WhoisActive
ORDER BY [start_time]
) AS D ORDER BY [start_time]
FOR XML PATH( 'tr' ), TYPE) AS VARCHAR(MAX)
)
-- Corrige a Formatação da Tabela
SET @AlertaLockTable = REPLACE( REPLACE( REPLACE( @AlertaLockTable, '<', '<'), '>', '>'), '<td>', '<td align = center>')
-- Títulos da Tabela do EMAIL
SET @AlertaLockTable =
'<table cellspacing="2" cellpadding="5" border="3">'
+ '<tr>
<th bgcolor=#0B0B61 width="140"><font color=white>[dd hh:mm:ss.mss]</font></th>
<th bgcolor=#0B0B61 width="100"><font color=white>Database</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Login</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Host Name</font></th>
<th bgcolor=#0B0B61 width="200"><font color=white>Hora Início</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Status</font></th>
<th bgcolor=#0B0B61 width="30"><font color=white>ID Sessão</font></th>
<th bgcolor=#0B0B61 width="60"><font color=white>ID Sessão Bloqueando</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Wait</font></th>
<th bgcolor=#0B0B61 width="60"><font color=white>Transações Abertas</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>CPU</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Reads</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Writes</font></th>
<th bgcolor=#0B0B61 width="300"><font color=white>Query</font></th>
</tr>'
+ REPLACE( REPLACE( @AlertaLockTable, '<', '<'), '>', '>')
+ '</table>'
--------------------------------------------------------------------------------------------------------------------------------
-- Insere um Espaço em Branco no EMAIL
--------------------------------------------------------------------------------------------------------------------------------
SET @EmptyBodyEmail = ''
SET @EmptyBodyEmail =
'<table cellpadding="5" cellspacing="5" border="0">' +
'<tr>
<th width="500"> </th>
</tr>'
+ REPLACE( REPLACE( ISNULL(@EmptyBodyEmail,''), '<', '<'), '>', '>')
+ '</table>'
/*******************************************************************************************************************************
-- Seta as Variáveis do EMAIL
*******************************************************************************************************************************/
SELECT @Importance = 'High',
@Subject = 'ALERTA: Existe(m) ' + CAST(@QtdProcessosBloqueados AS VARCHAR) +
' Processo(s) Bloqueado(s) a mais de ' + CAST((@Qt_Tempo_Lock) AS VARCHAR) + ' minuto(s)' +
' e um total de ' + CAST(@QtdProcessosBloqueadosLocks AS VARCHAR) + ' Lock(s) no Servidor: ' + @@SERVERNAME,
@EmailBody = @AlertaLockRaizHeader + @EmptyBodyEmail + @AlertaLockRaizTable + @EmptyBodyEmail
+ @AlertaLockHeader + @EmptyBodyEmail + @AlertaLockTable + @EmptyBodyEmail
/*******************************************************************************************************************************
-- ENVIA O EMAIL - ALERTA
*******************************************************************************************************************************/
EXEC [msdb].[dbo].[sp_send_dbmail]
@profile_name = 'MSSQLServer',
@recipients = '[email protected]',
@subject = @Subject,
@body = @EmailBody,
@body_format = 'HTML',
@importance = @Importance
/*******************************************************************************************************************************
-- Insere um Registro na Tabela de Controle dos Alertas -> Fl_Tipo = 1 : ALERTA
*******************************************************************************************************************************/
INSERT INTO [dbo].[Alerta] ( [Nm_Alerta], [Ds_Mensagem], [Fl_Tipo] )
SELECT 'Processo Bloqueado', @Subject, 1
END
END -- FIM - ALERTA
ELSE
BEGIN -- INICIO - CLEAR
IF @Fl_Tipo = 1
BEGIN
/*******************************************************************************************************************************
-- CRIA O EMAIL - CLEAR
*******************************************************************************************************************************/
--------------------------------------------------------------------------------------------------------------------------------
-- CLEAR - HEADER
--------------------------------------------------------------------------------------------------------------------------------
SET @AlertaLockHeader = '<font color=black bold=true size=5>'
SET @AlertaLockHeader = @AlertaLockHeader + '<BR /> Processos executando no Banco de Dados <BR />'
SET @AlertaLockHeader = @AlertaLockHeader + '</font>'
--------------------------------------------------------------------------------------------------------------------------------
-- CLEAR - BODY
--------------------------------------------------------------------------------------------------------------------------------
SET @AlertaLockTable = CAST( (
SELECT td = [Duração] + '</td>'
+ '<td>' + [database_name] + '</td>'
+ '<td>' + [login_name] + '</td>'
+ '<td>' + [start_time] + '</td>'
+ '<td>' + [status] + '</td>'
+ '<td>' + [session_id] + '</td>'
+ '<td>' + [blocking_session_id] + '</td>'
+ '<td>' + [Wait] + '</td>'
+ '<td>' + [open_tran_count] + '</td>'
+ '<td>' + [CPU] + '</td>'
+ '<td>' + [reads] + '</td>'
+ '<td>' + [writes] + '</td>'
+ '<td>' + [sql_command] + '</td>'
FROM (
-- Dados da Tabela do EMAIL
SELECT ISNULL([dd hh:mm:ss.mss], '-') AS [Duração],
ISNULL([database_name], '-') AS [database_name],
ISNULL([login_name], '-') AS [login_name],
ISNULL(CONVERT(VARCHAR(20), [start_time], 120), '-') AS [start_time],
ISNULL([status], '-') AS [status],
ISNULL(CAST([session_id] AS VARCHAR), '-') AS [session_id],
ISNULL(CAST([blocking_session_id] AS VARCHAR), '-') AS [blocking_session_id],
ISNULL([wait_info], '-') AS [Wait],
ISNULL(CAST([open_tran_count] AS VARCHAR), '-') AS [open_tran_count],
ISNULL([CPU], '-') AS [CPU],
ISNULL([reads], '-') AS [reads],
ISNULL([writes], '-') AS [writes],
ISNULL(SUBSTRING([sql_command], 1, 300), '-') AS [sql_command]
FROM #Resultado_WhoisActive
) AS D ORDER BY [start_time]
FOR XML PATH( 'tr' ), TYPE) AS VARCHAR(MAX)
)
-- Corrige a Formatação da Tabela
SET @AlertaLockTable = REPLACE( REPLACE( REPLACE( @AlertaLockTable, '<', '<'), '>', '>'), '<td>', '<td align = center>')
-- Títulos da Tabela do EMAIL
SET @AlertaLockTable =
'<table cellspacing="2" cellpadding="5" border="3">'
+ '<tr>
<th bgcolor=#0B0B61 width="140"><font color=white>[dd hh:mm:ss.mss]</font></th>
<th bgcolor=#0B0B61 width="100"><font color=white>Database</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Login</font></th>
<th bgcolor=#0B0B61 width="200"><font color=white>Hora Início</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Status</font></th>
<th bgcolor=#0B0B61 width="30"><font color=white>ID Sessão</font></th>
<th bgcolor=#0B0B61 width="60"><font color=white>ID Sessão Bloqueando</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Wait</font></th>
<th bgcolor=#0B0B61 width="60"><font color=white>Transações Abertas</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>CPU</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Reads</font></th>
<th bgcolor=#0B0B61 width="120"><font color=white>Writes</font></th>
<th bgcolor=#0B0B61 width="300"><font color=white>Query</font></th>
</tr>'
+ REPLACE( REPLACE( @AlertaLockTable, '<', '<'), '>', '>')
+ '</table>'
--------------------------------------------------------------------------------------------------------------------------------
-- Insere um Espaço em Branco no EMAIL
--------------------------------------------------------------------------------------------------------------------------------
SET @EmptyBodyEmail = ''
SET @EmptyBodyEmail =
'<table cellpadding="5" cellspacing="5" border="0">' +
'<tr>
<th width="500"> </th>
</tr>'
+ REPLACE( REPLACE( ISNULL(@EmptyBodyEmail,''), '<', '<'), '>', '>')
+ '</table>'
/*******************************************************************************************************************************
-- Seta as Variáveis do EMAIL
*******************************************************************************************************************************/
SELECT @Importance = 'High',
@Subject = 'CLEAR: Não existe mais algum Processo Bloqueado a mais de ' +
CAST((@Qt_Tempo_Lock) AS VARCHAR) + ' minuto(s) no Servidor: ' + @@SERVERNAME,
@EmailBody = @AlertaLockHeader + @EmptyBodyEmail + @AlertaLockTable + @EmptyBodyEmail
/*******************************************************************************************************************************
-- ENVIA O EMAIL - CLEAR
*******************************************************************************************************************************/
EXEC [msdb].[dbo].[sp_send_dbmail]
@profile_name = 'MSSQLServer',
@recipients = '[email protected]',
@subject = @Subject,
@body = @EmailBody,
@body_format = 'HTML',
@importance = @Importance
/*******************************************************************************************************************************
-- Insere um Registro na Tabela de Controle dos Alertas -> Fl_Tipo = 0 : CLEAR
*******************************************************************************************************************************/
INSERT INTO [dbo].[Alerta] ( [Nm_Alerta], [Ds_Mensagem], [Fl_Tipo] )
SELECT 'Processo Bloqueado', @Subject, 0
END
END -- FIM - CLEAR
END