SQL Server & PostgreSQL DBA & Dev Tips | MyTechMantra

Automated SQL Server Growth Alerts: Send HTML Reports via SQL Agent

Stop checking dashboards manually. Learn how to automate SQL Server growth alerts using T-SQL and HTML. This guide covers identifying ingestion spikes and sending formatted email reports via SQL Agent for a truly proactive DBA workflow.

How do you automate SQL Server growth alerts?

To automate SQL Server growth alerts, create a SQL Agent job that executes a T-SQL script comparing current row counts against historical snapshots. Use a CTE (Common Table Expression) to calculate the percentage change and the FOR XML PATH clause to format anomalies into an HTML table. Finally, use sp_send_dbmail to deliver the formatted report to your DBA team when growth exceeds a defined threshold (typically 10%).

The Problem: The "Dashboard Fatigue" Trap

In our previous guides, we built a historical capture system and a Power BI visualization layer. But let’s be real: as a DBA managing dozens of instances, you don’t have time to wake up and check every dashboard manually.

The biggest risk to a production environment isn't steady growth—it’s the unforeseen spike. Whether it’s a rogue application loop, a bulk import gone wrong, or an unmonitored log table, waiting until your disk space hits 0% is not a strategy; it's a crisis. You need an automated "Sentinel" that alerts you only when a table’s growth deviates from the norm.

The Solution: Proactive HTML Sentinel Alerts

The solution is a self-triggering SQL Server Agent job that compares your latest row count snapshot against the previous day's data. If the growth exceeds a specific threshold (e.g., 10%), the system generates a professional, CSS-styled HTML email and sends it directly to your inbox. This ensures you only react when action is required, effectively curing "Alert Fatigue."



Step 1: Prerequisites – Enabling the Messenger

Before we can send alerts, Database Mail must be configured. In my experience, it’s best to use a dedicated "Monitoring" profile to keep administrative alerts separate from application emails.

-- Quick Check: Is Database Mail Enabled?
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'Database Mail XPs', 1;
RECONFIGURE;

Step 2: The Logic – Anomaly Detection

We don't want an email for every table—only the ones that are "misbehaving." We define an anomaly as a table that has grown by more than X% and has a minimum size (to avoid alerting on tiny 10-row tables).

From the Trenches: Setting the Threshold

"I generally set my threshold at 10% for Production. However, for audit tables, you might set it lower. The script below uses a Common Table Expression (CTE) to calculate the 'delta' between the last two snapshots."



Step 3: The Master Script (HTML Engine)

This script does three things: identifies growth spikes, formats the results into a clean HTML table using FOR XML PATH, and sends the email via sp_send_dbmail.

DECLARE @EmailBody NVARCHAR(MAX);
DECLARE @TableRows NVARCHAR(MAX);

-- 1. Identify Growth Anomalies
;WITH GrowthCTE AS (
    SELECT 
        TableName,
        SchemaName,
        MAX(CASE WHEN RowID = 1 THEN RowCnt END) AS CurrentRows,
        MAX(CASE WHEN RowID = 2 THEN RowCnt END) AS PreviousRows,
        MAX(CASE WHEN RowID = 1 THEN ReservedMB END) AS CurrentSizeMB
    FROM (
        SELECT *, ROW_NUMBER() OVER (PARTITION BY TableName ORDER BY CaptureDate DESC) as RowID
        FROM dbo.TableRowCountHistory
    ) t
    WHERE RowID <= 2
    GROUP BY TableName, SchemaName
)
-- 2. Convert to HTML Table Rows
SELECT @TableRows = CAST((
    SELECT 
        td = SchemaName, '',
        td = TableName, '',
        td = FORMAT(PreviousRows, '#,0'), '',
        td = FORMAT(CurrentRows, '#,0'), '',
        td = CAST(((CurrentRows - PreviousRows) * 100.0 / NULLIF(PreviousRows, 0)) AS DECIMAL(10,2)), ''
    FROM GrowthCTE
    WHERE PreviousRows > 0 
      AND ((CurrentRows - PreviousRows) * 100.0 / PreviousRows) >= 10 -- 10% Threshold
    ORDER BY (CurrentRows - PreviousRows) DESC
    FOR XML PATH('tr'), TYPE 
) AS NVARCHAR(MAX));

-- 3. Wrap in HTML/CSS
IF @TableRows IS NOT NULL
BEGIN
    SET @EmailBody = N'<html><head><style>
        table { border-collapse: collapse; width: 100%; font-family: Calibri, sans-serif; }
        th { background-color: #00457c; color: white; padding: 10px; text-align: left; }
        td { border: 1px solid #ddd; padding: 8px; }
        tr:nth-child(even) { background-color: #f2f2f2; }
        .spike { color: #d9534f; font-weight: bold; }
        </style></head><body>
        <h2>⚠️ SQL Server Table Growth Alert</h2>
        <p>The following tables have exceeded the 10% daily growth threshold:</p>
        <table>
            <tr><th>Schema</th><th>Table</th><th>Prev Rows</th><th>Curr Rows</th><th>Growth %</th></tr>' 
            + @TableRows + 
        N'</table><p>Please check the <a href="YOUR_POWER_BI_LINK">Growth Dashboard</a> for more details.</p>
        </body></html>';

    EXEC msdb.dbo.sp_send_dbmail
        @profile_name = 'DBA_Alerts',
        @recipients = 'dba-team@yourcompany.com',
        @subject = 'Alert: Sudden Database Growth Detected',
        @body = @EmailBody,
        @body_format = 'HTML';
END

Step 4: Scheduling via SQL Agent

To ensure you aren't manually running this, create a SQL Server Agent Job:

  1. Name: Monitor_Table_Growth_Alerts
  2. Step: Paste the script above.
  3. Schedule: Set it to run 1 hour after your data collection job from Part 1.

Best Practices for Expert Alerting

  • Threshold Tuning: Use a variable for the percentage threshold. For high-volume OLTP systems, you might need a 20% threshold to avoid noise.
  • Minimum Row Count: Always filter out small tables. A table growing from 1 row to 2 rows is a 100% growth rate but is rarely an emergency. Add AND CurrentRows > 10000 to your WHERE clause.
  • Distribution Lists: Never send alerts to individual emails. Send them to a Distribution List (DL) or a Slack/Teams-connected inbox to ensure the whole team has visibility.
  • HTML Links: Notice in the script I included a link back to the Power BI dashboard from Article 2. This creates a seamless workflow: Email Alert -> Dashboard Analysis -> Remediation.

Conclusion

You have now moved from a reactive state to a fully automated monitoring ecosystem. By combining historical tracking, Power BI trend analysis, and automated SQL Server growth alerts HTML email notifications, you've built an enterprise-grade capacity planning suite.

These automated database capacity notifications don't just save time; they protect the business from downtime. Being able to provide a T-SQL script for growth anomaly detection that delivers professional reports is what separates a standard DBA from a Senior Data Architect. You now have the tools to explain the "What," "Why," and "When" of your data's future.

Next Steps


Frequently Asked Question (FAQs) on Automated SQL Server HTML Alerts

1. How do you send HTML formatted email from SQL Server?

To send HTML formatted email from SQL Server, you must use the sp_send_dbmail stored procedure with the @body_format parameter set to 'HTML'. The email body itself is constructed using T-SQL string concatenation and the FOR XML PATH clause, which transforms raw query results into a structured HTML <table>. Adding inline CSS within a <style> tag allows you to brand the report and highlight critical growth anomalies.

2. What is the best SQL Server table growth alert script for capacity planning?

The best SQL Server table growth alert script uses a Common Table Expression (CTE) to compare the most recent row count snapshot against the previous day's data. By calculating the percentage difference between snapshots, the script can filter out "noise" and only alert the DBA when a table exceeds a predefined growth threshold (such as 10% or 20%). This proactive approach is essential for modern database capacity planning.

3. How can I create a SQL Server Agent job for row count alerts?

Creating a SQL Server Agent job for row count alerts involves three steps: first, define a T-SQL step that identifies growth spikes; second, integrate sp_send_dbmail to deliver the findings; and third, schedule the job to run daily. It is a best practice to schedule this job shortly after your data collection task to ensure the alert logic is analyzing the freshest metadata available.

4. Can a T-SQL script for growth anomaly detection prevent disk space issues?

Yes, a T-SQL script for growth anomaly detection acts as an early warning system. While standard disk alerts trigger when space is already low, growth anomaly alerts notify you the moment a table begins to ingest data at an unusual rate. This allows DBAs to intervene, archive data, or expand volumes before the server reaches a critical "Disk Full" state.

5. How do I automate database capacity notifications for a large SQL estate?

To automate database capacity notifications across multiple instances, you should centralize your row count history into a single management database. By adding a ServerName column to your tracking table, one master SQL Agent job can analyze growth trends for the entire estate and send a unified HTML report, reducing the administrative overhead of managing individual alerts on every server.

6. Why use the FOR XML PATH clause in SQL Server email alerts?

The FOR XML PATH clause is the "engine" that converts relational SQL data into the HTML tags (<tr> and <td>) required for email reports. It is significantly more efficient and cleaner than using cursors or complex loops to build strings. When combined with TYPE, it handles special characters safely, ensuring your SQL Server growth alerts HTML email renders correctly in all mail clients like Outlook or Gmail.

Ashish Kumar Mehta

Ashish Kumar Mehta is a database manager, trainer and technical author. He has more than a decade of IT experience in database administration, performance tuning, database development and technical training on Microsoft SQL Server from SQL Server 2000 to SQL Server 2014. Ashish has authored more than 325 technical articles on SQL Server across leading SQL Server technology portals. Over the last few years, he has also developed and delivered many successful projects in database infrastructure; data warehouse and business intelligence; database migration; and upgrade projects for companies such as Hewlett-Packard, Microsoft, Cognizant and Centrica PLC, UK. He holds an engineering degree in computer science and industry standard certifications from Microsoft including MCITP Database Administrator 2005/2008, MCDBA SQL Server 2000 and MCTS .NET Framework 2.0 Web Applications.

Add comment

AdBlocker Message

Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.


Newsletter Signup! Join 15,000+ Professionals




Be Social! Like & Follow Us

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.

Advertisement