You may face a case where you need to send an email with some summary information based on certain DB tables that you have in place. The best presentation of this is to present the data in tabular way in your email. In the past, to satisfy this requirement you had to build your own .NET or Java code and write long algorithm to accomplish this. Which is a time consuming for such a small requirement… don’t agree?
Now you can do it in very easy way using SQL server mail feature. Within couple of lines of SQL statements you can send a very good looking email to your recipient list… below is a summary of steps of how you can do it:
- Build a temporary table on your DB to hold your result sent.
- Populate the temporary table with your summary data records.
- Do some sort of conversion to convert your table data into an XML.
- Build your HTML header and concatenate the result of step 3 into your body html tag
- Do send the email using SQL server mail.
Below is a sample code to accomplish the job
CREATE TABLE #Temp
INSERT INTO #Temp
SELECT ‘San Diego’,500
SELECT ‘Los Angeles’,100
DECLARE @xml NVARCHAR(MAX)
DECLARE @body NVARCHAR(MAX)
SET @xml = CAST(( SELECT [Area] AS ‘td’,”,[ SaleCount] AS ‘td’,
FROM #Temp ORDER BY [Area]
FOR XML PATH(‘tr’), ELEMENTS ) AS NVARCHAR(MAX))
SET @body ='<html><body><H3>Sales Summary Report</H3>
<table border = 1>
<th> Area </th> <th>Sales Count </th> </tr>’
SET @body = @body + @xml +'</table></body></html>’
@profile_name = ‘SQLProfileName’, — replace with your SQL Database Mail Profile
@body = @body,
@recipients = ‘email@example.com’, — replace with your email address
@subject = ‘Sales Summary Report – Tabular Format ‘ ;
DROP TABLE #Temp