Send email does not printing query result in csv

时间:2015-11-12 11:01:40

标签: sql sql-server email

I'm using following code to send an attachment in email in CSV format, this is working fine but when i try to use the original query i-e select col1, col2, col3 .. from DBTable in place of test query select ''1'', ''2'', ''3'', ''4'' email is not being sent, even there is not any error but email not being sent, stored procedure get executed in the same way with both queries.

EXEC msdb..sp_send_dbmail @profile_name='Notificatins and Alerts',
    @recipients = @EmailRecipient,
    @subject = @MessageSubject,
    @body = @MessageBody,
    @body_format = 'HTML',
    @query='SET NOCOUNT ON;
            select ''sep=,''            
            select ''1'', ''2'', ''3'', ''4''  ',
--select ''1'', ''2'', ''3'', ''4'' 
    @attach_query_result_as_file=1,
    @query_attachment_filename = 'Results.csv',
    @query_result_separator =',',
    @query_result_no_padding=1, --trim
    --@query_result_width=32767,  --stop wordwrap
    @exclude_query_output =1,
    @append_query_error = 0,
    @query_result_header =0;

can any one help me on that.

1 个答案:

答案 0 :(得分:0)

Here is the solution. Hope this will help someone:

EXEC msdb..sp_send_dbmail @profile_name='Notificatins and Alerts',
    @recipients = @EmailRecipient,
    @subject = @MessageSubject,
    @body = @MessageBody,
    @body_format = 'HTML',
    @query='SET NOCOUNT ON;
            select ''sep=,''            
            select col1, col2, col3 .. from dbName.dbo.DBTable  ',
--select ''1'', ''2'', ''3'', ''4'' 
    @attach_query_result_as_file=1,
    @query_attachment_filename = 'Results.csv',
    @query_result_separator =',',
    @query_result_no_padding=1, --trim
    --@query_result_width=32767,  --stop wordwrap
    @exclude_query_output =1,
    @append_query_error = 0,
    @query_result_header =0;

simply one have to use DBName.dbo with table name that was missing in my query.