Hi Folks,
It would be nice to have SQL send email notifications that are HTML based with HTML formatting
Introduction
This is possible because of the following. HTML tables are made of Tags called TD and TR, in SQL we have the FOR XML statement and we can actually cheat the SQL server into thinking that it is creating a XML layout where in fact it is building a HTML table layout.
Below is a sample email sent by SQL Server
Notice the failure column, here we have different colours, if there are errors, it sets the background to Red.
SQL Code
Below is the SQL Procedure that does this.
USE [btwf_BizTalkWorkFlowSupport] ———————— FAILED RECORDS ———————————————– IF (OBJECT_ID(‘#tmpDailyReport’) IS NOT NULL) CREATE TABLE #tmpDailyReport( INSERT INTO #tmpDailyReport( DECLARE @tableHTML NVARCHAR(MAX) ; SET @tableHTML = SELECT td = Date, ”, td = WebServerName, ”, td = Location, ”, td = cnt_RecsTotal, ”, ) AS NVARCHAR(MAX) ) + drop table #tmpDailyReport declare @RecipientList as varchar(max) EXEC msdb.dbo.sp_send_dbmail |
Analysis
The Magic is done here:
SELECT td = Date, ”, td = WebServerName, ”, td = Location, ”, td = cnt_RecsTotal, ”,
‘td/@bgcolor’ = CASE WHEN cnt_RecsFailed > 0 THEN ‘#FF3366’ END,
td = cnt_RecsFailed
FROM #tmpDailyReport
for xml path(‘tr’), TYPE
To understand it, break it down, this query above generates an XML document, that we inject into the HTML variable. Lets see what it looks like with the for XML statement.
I run the Query below, omitting the for XML path statement:
Result:
Now with the XML Statement. I tell the statement that the path is ‘tr’:
This means that for every Column a root element called ‘tr’ is created, and then the column data and name is injected. We can then decorate this output into a nice HTML page, as the output is just an HTML Table, and that is what we do here.
We then just concatenate the output from our HTML table generator code to the above statement with a Cast.
Conclusion
With a bit of an imagination, you can generate HTML with SQL Server, since they both tag based languages, so I hope this article will bring colour and life to your SQL email notifications.
Note: You do not need the Type declaration in the FOR XML clause, so
for xml path(‘tr’), TYPE
can be
for xml path(‘tr’)
Just a matter of personnel choice.
- Uncategorized