Sql server Db Mail which can send mail for two or more queries

自作多情 提交于 2019-12-12 17:06:25

问题


I want to send db mail , which contains the result of two queries, how do I make it happen?

USE msdb
EXEC sp_send_dbmail
  @profile_name = 'try01',
  @recipients = 'yyyyy@yyy.com',
  @subject = 'Table Values',
  @body = 'xxxxxxxxxxxxxx.',
  @execute_query_database = 'Reports',
  @query = 'SELECT * from Table'

回答1:


OK, This was easy as if you put a semicolon the result of both the queries are sent. Here it is:

USE msdb
EXEC sp_send_dbmail
  @profile_name = 'try01',
  @recipients = 'yyyyy@yyy.com',
  @subject = 'Table Values',
  @body = 'xxxxxxxxxxxxxx.',
  @execute_query_database = 'Reports',
  @query = 'SELECT * from Table; select * from table2'

Only problem I have now is to get this into a decent looking format.




回答2:


sp_send_dbmail on MSDN shows a single @query parameter
So you can send one query only unless you can use UNION to join result sets.

Or save the query results to disk and then set @file_attachments (I wouldn't, personally)

Or use Reporting Services to query and send the email as a report




回答3:


Put your queries into a Stored Procedure and then call it in the query line.

Sample stored proc:

CREATE PROCEDURE build_email_as_query
AS
BEGIN

    SET NOCOUNT ON;

    -- newline var

    declare @lf char(6)
    set     @lf = '<br />'

    -- build the email

    select @lf + @lf

    select 'results 1' + @lf    
    select 'results 2' + @lf    
    select 'results 3' + @lf    

END
GO

exec sp_send_dbmail:

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'profileName', 
    @body = 'Results of query: <br /><br />',
    @body_format ='HTML',
    @recipients = 'test@domain.com',
    @copy_recipients = '',
    @subject = 'testing emails',
    @execute_query_database = 'DatabaseName',
    @query = 'exec build_email_as_query'


来源:https://stackoverflow.com/questions/16458610/sql-server-db-mail-which-can-send-mail-for-two-or-more-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!