Blog

How to send a Scheduled HTML report directly from SQL Server

By Gabriel Palma

 

The situation

A customer asked recently for a quick daily report of about-to-expire items, he wanted something simple that could be sent via email to the people already registered in the database. Acquiring the information was very simple (as simple as writing a query). The problem was getting those results inside an email and sending it automatically every day.

We came up with a scheduled SQL Server job running daily, getting and shipping the results without passing through .Net code.

 

The steps

Step 1. Write the query to retrieve the raw data.

 

I used AdventureWorks database for the following example. Here I’ll get a report of work orders with due date greater than a specific date. In the practice, it should be greater than the current date but my database doesn’t have information after Jan 1st, 2005, so I’m using a specific date only to get the results.

So this is the query:

ScheduledHTML-1.jpg

And these are the results:

ScheduledHTML-2.jpg

Step 2. Run the query and ship the results

 

SQL Server (since 2005) has a stored procedure to send emails directly from the database. SQL Mail must be configured and running in the server for this stored procedure to work.

Using msdb.dbo.sp_send_dbmail you can send the results of a query as an email as simple as follows:

 

ScheduledHTML-3.jpg

And this is how it looks in Outlook:

ScheduledHTML-4.jpg

It’s that simple.

 

Step 3. Behold!

 

Obviously those results need to look nice if your customer’s clients (and their clients) are willing to receive it.

In order to turn this report into a something more professional looking the best option is sending that as html. That’s another nice feature of the msdb.dbo.sp_send_dbmail stored procedure. Combining that option and the XML capabilities of SQL Server, I wrote a stored procedure to transform the results into an HTML table and returning characters.

This is the stored procedure:

ScheduledHTML-5.jpg

 

The result of the previous stored procedure is the raw html report. Take a look at the “for xml path(‘tr’)” part of the query, which is simply creating the tr-td tags structure of the table.

Run the report like this:

ScheduledHTML-6.jpg

 

This is what I got now:

ScheduledHTML-7.jpg

 

Even better: add styling to the html you already have in the stored procedure in this way:

ScheduledHTML-8.jpg

 

This is how it looks in the end:

ScheduledHTML-9.jpg

Step 4. Schedule it and see it work

 

Since this a simple query it can be included in any SQL job. It’s not difficult to get a list of recipients with their email addresses and create a cycle to execute the msdb.dbo.sp_send_dbmail procedure within the same job.

Finally, schedule the job to run as frequently as necessary and get a daily report directly from SQL.

 

Comments

Leave a comment

 
 
 
 
CAPTCHA Image Validation