Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
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 
@qSELECT = N'SELECT TOP 100',
    @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: 1801 | Views in the last 30 days: 40
 
Related Articles
FORUM

What is the best way to FTP query results?

FTP the results from a stored procedure query

SCRIPT

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

Query results splitter

FORUM

Copy query result issue

Copy query result issue

FORUM

Problem with query result

Query result out of......

FORUM

Creating view from stored procedure results

Creating view from stored procedure results

Tags
database mail    
db_mail    
html    
stored procedure    
 
Contribute

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones