DECLARE @sub VARCHAR(100);
DECLARE @qry VARCHAR(1000);
DECLARE @msg VARCHAR(250);
DECLARE @query NVARCHAR(1000);
DECLARE @query_attachment_filename NVARCHAR(520);
SELECT @sub = 'This is a test.';
SELECT @msg = 'Please refer to the attached csv for the result.';
SELECT @query = 'SET NOCOUNT ON;
SELECT * FROM table01 WITH(NOLOCK)';
SELECT @query_attachment_filename = 'test.csv';
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'MyProfile',
@recipients = 'me@company.com',
@copy_recipients = '',
@body = @msg,
@subject = @sub,
@query = @query,
@query_attachment_filename = @query_attachment_filename,
@attach_query_result_as_file = 1,
@query_result_header = 1,
@query_result_width = 256,
@query_result_separator = ' ',
@query_result_no_padding = 1;
Comments