SQL Clone
SQLServerCentral is supported by Redgate
Log in  ::  Register  ::  Not logged in

Get your favorite SSC scripts directly in SSMS with the free SQL Scripts addin. Search for scripts directly from SSMS, and instantly access any saved scripts in your SSC briefcase from the favorites tab.
Download now (direct download link)

SP Send Query Result as HTML table using DBMail

By Dave Gugg,

This script will create a stored procedure that can be used to send dbMail with query results in an html table.  For ease of use I've broken the query parts out into separate parameters.  The list of fields being returned should be delimited using the pipe character |.  

There are other sources that explain how to include query results as an html table.  The focus of this script is to create a stored procedure that is easy to use.  The stored procedure is also set up to not send emails if no results are returned from the query.  Note that all objects must be fully qualified (database.schema.object) and parts of the query that are not needed are optional.

A sample call would be:

EXEC DBADatabase.dbo.SendDBEmailwithTabularQuery 
    @fieldlist = N' COUNT(tC.Client_ID) AS ClientCount|LEFT(tC.Client_FullName,2) AS ShortClientName|tB.AssociatesId',
    @qFROM = N'FROM database.dbo.Clients tC
INNER JOIN database.dbo.Associates tB ON tB.AssociatesId = tC.AssociatesId', 
    @qWHERE = N'WHERE tC.Deleted =0', 
@qGroupBy = N'GROUP BY LEFT(tC.Client_FullName,2), tB.AssociatesId',
--@qHaving = N'HAVING COUNT(tC.Client_ID)>2',
    @qOrderBy = N'ORDER BY tB.AssociatesId', 
    @recipients = N'david.gugg@SQLServerCentral.com',
    @subject = N'email test',
    @Title = N'Query Results' 

Total article views: 3551 | Views in the last 30 days: 5
Related Articles

What is the best way to FTP query results?

FTP the results from a stored procedure query


Split by a row (count) number of a query results

Query results splitter


Copy query result issue

Copy query result issue


Problem with query result

Query result out of......


Creating view from stored procedure results

Creating view from stored procedure results

database mail    
stored procedure