在部署了数据库镜像之后,我们需要监控参与镜像的主数据库和镜像数据库的状态,如果状态异常,发送告警邮件。那么这个脚本需要在主和镜像服务器上都运行。
目录视图sys.database_mirroring对SQL Server实例上的每个数据库都包含一行(包括系统数据库和未配置镜像的数据库),当然也包含所有镜像数据库的状态信息。我们可以查询该目录视图,对于每个异常状态的镜像数据库触发告警邮件。笔者的环境配置的是异步镜像,依赖于手动故障转移。
前提条件:
1. 配置好数据库邮件,有正确的Profile。
2. 有权限发送邮件的有效Login,需要是msdb数据库中DatabaseMailUserRole角色成员。
3. 一对用于监控的镜像数据库。
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
|
DECLARE
@state
VARCHAR
(30)
DECLARE
@DbMirrored
INT
DECLARE
@DbId
INT
DECLARE
@String
VARCHAR
(100)
DECLARE
@databases
TABLE
(DBid
INT
, mirroring_state_desc
VARCHAR
(30))
-- get status for mirrored databases
INSERT
@databases
SELECT
database_id, mirroring_state_desc
FROM
sys.database_mirroring
WHERE
mirroring_role_desc
IN
(
'PRINCIPAL'
,
'MIRROR'
)
AND
mirroring_state_desc
NOT
IN
(
'SYNCHRONIZED'
,
'SYNCHRONIZING'
)
-- iterate through mirrored databases and send email alert
WHILE
EXISTS (
SELECT
TOP
1 DBid
FROM
@databases
WHERE
mirroring_state_desc
IS
NOT
NULL
)
BEGIN
SELECT
TOP
1 @DbId = DBid, @State = mirroring_state_desc
FROM
@databases
SET
@string =
'Host: '
+@@servername+
'.'
+
CAST
(DB_NAME(@DbId)
AS
VARCHAR
)+
' - DB Mirroring is '
+@state +
' - notify DBA'
EXEC
msdb.dbo.sp_send_dbmail
'valid_mail_profile'
,
'DBA@xxx.com'
, @body = @string, @subject = @string
DELETE
FROM
@databases
WHERE
DBid = @DbId
END
--also alert if there is no mirroring just in case there should be mirroring :)
SELECT
@DbMirrored =
COUNT
(*)
FROM
sys.database_mirroring
WHERE
mirroring_state
IS
NOT
NULL
IF
@DbMirrored = 0
BEGIN
SET
@string =
'Host: '
+@@servername+
' - No databases are mirrored on this server - notify DBA'
EXEC
msdb.dbo.sp_send_dbmail
'valid_mail_profile'
,
'DBA@xxx.com'
, @body = @string, @subject = @string
END
|
依赖于手动故障转移。将以上脚本放到主服务器和镜像服务器上的作业里,每5分钟执行一次。
收到邮件效果如下:
本文转自UltraSQL51CTO博客,原文链接: http://blog.51cto.com/ultrasql/1906242,如需转载请自行联系原作者