从SQL中的两个不同查询中发送两个不同的附件

时间:2017-10-04 12:30:12

标签: sql sql-server-2008

我想从两个不同的查询中附加两个不同的文件;这是我的代码导致此问题标题中提到的错误:

EXEC msdb.dbo.sp_send_dbmail 
     @profile_name='MyTestMail
     @body = @body,
     @body_format ='HTML',
     @recipients = 'xyz@zyx.com',
     @subject = @SBJ,
     @importance = HIGH,
     @sensitivity= Confidential,
     @query = 'Select * from XXXXXXXX;',
     @attach_query_result_as_file = 1,
     @query_attachment_filename = 'X1.csv',
     @query_result_separator=',',
     @query_result_width =32767,
     @query_result_no_padding=1,
     @query = 'Select * from XXXXXXXX2;',
     @attach_query_result_as_file = 1,
     @query_attachment_filename = 'X2.csv',
     @query_result_separator=',',
     @query_result_width =32767,
     @query_result_no_padding=1;

如果不重复查询XXXXXXXX2,我可以成功从同一代码发送一个文件作为附件。

2 个答案:

答案 0 :(得分:0)

只有从文件系统附加多个文件时才能附加这些文件。 请参阅以下语法 -

 sp_send_dbmail [ [ @profile_name = ] 'profile_name' ]  
        [ , [ @recipients = ] 'recipients [ ; ...n ]' ]  
        [ , [ @copy_recipients = ] 'copy_recipient [ ; ...n ]' ]  
        [ , [ @blind_copy_recipients = ] 'blind_copy_recipient [ ; ...n ]' ]  
        [ , [ @from_address = ] 'from_address' ]  
        [ , [ @reply_to = ] 'reply_to' ]   
        [ , [ @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 ]  

答案 1 :(得分:0)

显然两次运行@attach_query_result_as_file = 1无效。如果您无法从文件系统发送附件,那么我能想到的唯一解决方法是使用@attach_query_result_as_file在电子邮件正文中以html格式显示第一个查询结果,然后仅将第二个查询结果作为附件显示。 。我使用这种策略发送每日电子邮件报告。

enter image description here