Solved

How do i send the query results using SQL 2005 and Database Mail

Posted on 2008-06-19
7
750 Views
Last Modified: 2012-05-05
I have database mail setup and I can send myself a test message in either text or html... but when I try to send a query as the message, the email fails.

This is my test code that works:


DECLARE @Message AS VARCHAR(100)
SET @Message ='Server :' + @@servername+ ' My First Database Email '
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'LOGON',
@subject = 'Testing',
@recipients = 'email address here',
@body_format = 'TEXT',
@body = @message,


This is my testcode that fails

DECLARE @Message AS VARCHAR(100)
SET @Message ='Server :' + @@servername+ ' My First Database Email '
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'LOGON',
@subject = 'Testing',
@recipients = 'email address here',
@body_format = 'TEXT',
@body = @message,
@Query = 'Select * from [Jason_DB].[dbo].[Sales_JobEntry]'

0
Comment
Question by:logoncom
  • 4
  • 3
7 Comments
 
LVL 60

Expert Comment

by:chapmandew
ID: 21824086
Do you have permission to run the query listed in the stored procedure?
0
 

Author Comment

by:logoncom
ID: 21824432
I wasnt trying to access a sp, will it only work with sprocs?

Yes, I have full access
0
 
LVL 60

Expert Comment

by:chapmandew
ID: 21824443
i meant the msdb.dbo.sp_send_dbmail stored procedure.

Make sure your database mail profile is public.
0
Zoho SalesIQ

Hassle-free live chat software re-imagined for business growth. 2 users, always free.

 

Author Comment

by:logoncom
ID: 21824477
The profile is public.  I can send email... I have already tried... my problem is I do not know how to send query results as the body of the email.
0
 
LVL 60

Expert Comment

by:chapmandew
ID: 21824511
You're getting an error when you do, right?  What is the error?
0
 

Author Comment

by:logoncom
ID: 21824553
I get bad syntax or wrong variable etc... problem is I dont know how to tell database mail to send the results of the qeury as the body of the email and not a message.

How would I email:  Select * from Table where field = 'xyz'
0
 

Accepted Solution

by:
logoncom earned 0 total points
ID: 21826245
In case anyone wants the solution to this... I figured it out myself


--sp_send_dbmail
--    [ [ @profile_name = ] 'profile_name' ]
--    [ , [ @recipients = ] 'recipients [ ; ...n ]' ]
--    [ , [ @copy_recipients = ] 'copy_recipient [ ; ...n ]' ]
--    [ , [ @blind_copy_recipients = ] 'blind_copy_recipient [ ; ...n ]' ]
--    [ , [ @subject = ] 'subject' ]
--    [ , [ @body = ] 'body' ]
--    [ , [ @body_format = ] 'body_format' ]
--    [ , [ @importance = ] 'importance' ]
--    [ , [ @sensitivity = ] 'sensitivity' ]
--    [ , [ @file_attachments = ] 'attachment [ ; ...n ]' ]
--    [ , [ @query = ] 'query' ]
--    [ , [ @execute_query_database = ] 'execute_query_database' ]
--    [ , [ @attach_query_result_as_file = ] attach_query_result_as_file ]
--    [ , [ @query_attachment_filename = ] query_attachment_filename ]
--    [ , [ @query_result_header = ] query_result_header ]
--    [ , [ @query_result_width = ] query_result_width ]
--    [ , [ @query_result_separator = ] 'query_result_separator' ]
--    [ , [ @exclude_query_output = ] exclude_query_output ]
--    [ , [ @append_query_error = ] append_query_error ]
--    [ , [ @query_no_truncate = ] query_no_truncate ]
--    [ , [ @query_result_no_padding = ] query_result_no_padding ]
--    [ , [ @mailitem_id = ] mailitem_id ] [ OUTPUT ]


--QUERY EMAIL MESSAGE

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'Profile',
    @recipients = 'recipientsemail@email.com',
    @query = 'SELECT * FROM TableName' ,
    @subject = 'Work Order Count',
    @attach_query_result_as_file = 0 ;


--HTML EMAIL MESSAGE

DECLARE @tableHTML  NVARCHAR(MAX) ;

SET @tableHTML =
    N'<H1>Work Order Report</H1>' +
    N'<table border="1">' +
    N'<tr><th>Work Order ID</th><th>Product ID</th>' +
    N'<th>Name</th><th>Order Qty</th><th>Due Date</th>' +
    N'<th>Expected Revenue</th></tr>' +
    CAST ( ( SELECT td = wo.WorkOrderID,       '',
                    td = p.ProductID, '',
                    td = p.Name, '',
                    td = wo.OrderQty, '',
                    td = wo.DueDate, '',
                    td = (p.ListPrice - p.StandardCost) * wo.OrderQty
              FROM AdventureWorks.Production.WorkOrder as wo
              JOIN AdventureWorks.Production.Product AS p
              ON wo.ProductID = p.ProductID
              WHERE DueDate > '2004-04-30'
                AND DATEDIFF(dd, '2004-04-30', DueDate) < 2
              ORDER BY DueDate ASC,
                       (p.ListPrice - p.StandardCost) * wo.OrderQty DESC
              FOR XML PATH('tr'), TYPE
    ) AS NVARCHAR(MAX) ) +
    N'</table>' ;

EXEC msdb.dbo.sp_send_dbmail @recipients='danw@Adventure-Works.com',
    @subject = 'Work Order List',
    @body = @tableHTML,
    @body_format = 'HTML' ;


--send email

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'AdventureWorks Administrator',
    @recipients = 'danw@Adventure-Works.com',
    @body = 'The stored procedure finished successfully.',
    @subject = 'Automated Success Message' ;
0

Featured Post

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
MS SQL - Rotating Values in SQL 9 53
SQL Server Deadlocks 12 50
How to identify differences between 2 backup files? 7 31
SSRS troubles 4 20
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.
This videos aims to give the viewer a basic demonstration of how a user can query current session information by using the SYS_CONTEXT function

895 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now