Automating Suspect Pages Monitoring in SQL Server with Email Alerts

Introduction

Database corruption is one of the most critical issues in SQL Server, and detecting suspect pages early can help prevent data loss and downtime. SQL Server logs suspect pages in msdb.dbo.suspect_pages whenever it encounters corruption issues like torn pages, checksum failures, or I/O errors. In this article, I’ll share a simple yet effective SQL script that automates the detection of suspect pages and sends an HTML-formatted email report to database administrators.

SQL Script for Suspect Pages Alert

The following SQL script checks for suspect pages in SQL Server and sends an email alert with the details when any are found. Additionally, it deletes suspect page records older than 90 days to maintain a clean log.

DECLARE @count INTEGER;

DECLARE @tableHTML NVARCHAR(MAX);

DECLARE @subj NVARCHAR(100);

SELECT @count = COUNT(1) FROM msdb.dbo.suspect_pages;

SET @subj = 'Suspect Pages Found in ' + @@SERVERNAME;

SET @tableHTML =

    N'<H1>Suspect Pages Found in ' + @@SERVERNAME + ', details are below.</H1>' +

    N'<table border="1">' +

    N'<tr><th>Database ID</th><th>Database</th>' +

    N'<th>File ID</th><th>File</th><th>Page ID</th>' +

    N'<th>Event Desc</th><th>Error Count</th><th>Last Updated</th></tr>' +

    CAST((SELECT td = sp.database_id, '',

                 td = d.name, '',

                 td = sp.file_id, '',

                 td = mf.physical_name, '',

                 td = sp.page_id, '',

                 td = CASE

                         WHEN sp.event_type = 1 THEN '823 or 824 error other than a bad checksum or a torn page'

                         WHEN sp.event_type = 2 THEN 'Bad checksum'

                         WHEN sp.event_type = 3 THEN 'Torn Page'

                         WHEN sp.event_type = 4 THEN 'Restored (The page was restored after it was marked bad)'

                         WHEN sp.event_type = 5 THEN 'Repaired (DBCC repaired the page)'

                         WHEN sp.event_type = 7 THEN 'Deallocated by DBCC'

                     END, '',

                 td = sp.error_count, '',

                 td = sp.last_update_date

          FROM msdb.dbo.suspect_pages sp

          INNER JOIN sys.databases d ON d.database_id = sp.database_id

          INNER JOIN sys.master_files mf ON mf.database_id = sp.database_id AND mf.file_id = sp.file_id

          FOR XML PATH('tr'), TYPE) AS NVARCHAR(MAX)) +

    N'</table>';

IF @count > 0

BEGIN

    EXEC msdb.dbo.sp_send_dbmail

        @recipients = N'bandaruajeyudu@outlook.com',

        @body = @tableHTML,

        @subject = @subj,

        @body_format = 'HTML',

        @profile_name = 'SQLMail';

END

DELETE FROM msdb.dbo.suspect_pages WHERE last_update_date < GETDATE() - 90;

--Note: To ensure this script works correctly, you need to configure Database Mail in SQL Server.

No comments:

Post a Comment