Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a query result in CSV format?

Tags:

sql

ssis

I am working on ETL and I have this below sql code in my SQL Task in SSIS package. This is how i have coded. I am selecting a data from a table and result of that query as file. I want this attachment sent in CSV format. How do i do it?

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

Any help will be very appreciated. Thanks in advance.

like image 593
ETLUser Avatar asked Mar 04 '13 19:03

ETLUser


People also ask

How do I convert a SQL result to a CSV file?

Export SQL Server data to CSV by using the ApexSQL Complete Copy results as CSV option. The Copy code as is a feature in ApexSQL Complete, add-in for SSMS and Visual Studio, that copy the data from the Results grid to a clipboard in one of the following data files: CSV, XML, HTML in just one click.


2 Answers

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

like image 148
JodyT Avatar answered Sep 21 '22 15:09

JodyT


@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;
like image 31
ossie Avatar answered Sep 22 '22 15:09

ossie