How to send a query result in CSV format?

Adding @query_result_separator should do the trick.

EXEC sp_send_dbmail @profile_name='default',
@recipients='[email protected]',
@subject=@SUB,
@body=@BODY,

@query= 'SELECT [MID],[HID],[MeC],[LC],[RowCDate]
FROM [JBC].[dbo].[Table1] WHERE RowCDate >= GETDATE()
',
@attach_query_result_as_file = 1,
@query_attachment_filename   = 'Results.csv',
@query_result_separator      = ','

Adding @query_result_no_padding = 1 might clean up the results a bit. All off the arguments can be found here


@query='
SET NOCOUNT ON;
select ''sep=;''
select ''Col1'',''Col2'',''Col3'',''Col3''

select CONVERT(NVARCHAR,Col1),ISNULL(Col2, ''''),Col4
FROM ...
SET NOCOUNT OFF;
',

--Additional settings
@query_attachment_filename   = '*.csv',
@query_result_separator      = ';',
@attach_query_result_as_file = 1,
@query_result_no_padding     = 1,
@exclude_query_output        = 1,
@append_query_error          = 0,
@query_result_header         = 0;

Tags:

Sql

Ssis