How to send a query result in CSV format?

2019-04-05 01:58发布

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='dev@null.com',
@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.

标签: sql ssis
5条回答
劫难
2楼-- · 2019-04-05 02:29
@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;
查看更多
Lonely孤独者°
3楼-- · 2019-04-05 02:29

Inside a proc:

`SELECT 
table.myColumn AS [sep=, 
myColumn]
, table.myCol2
, table.myCol3...`

with a normal hard return within the column alias after "sep=,".

查看更多
别忘想泡老子
4楼-- · 2019-04-05 02:31

This comment on purple frog indicates you can also use the tab character as a delimiter.

Also looks like this answer's been posted already, my bad: https://stackoverflow.com/a/44315682/5758637

(Copying and pasting in case the purple frog link goes dead in the future):

DECLARE @tab char(1) = CHAR(9)
EXEC msdb.dbo.sp_send_dbmail  
@profile_name='donotreply' 
,@recipients ='xx@x'  
,@query= @query  
,@subject= 'xx'  
,@attach_query_result_as_file=1    
,@query_attachment_filename='xx.csv'    
,@query_result_separator=@tab
,@query_result_no_padding=1 –trim
,@query_result_width=32767 –stop wordwrap
查看更多
时光不老,我们不散
5楼-- · 2019-04-05 02:32

Adding

'[sep=,' + CHAR(13) + CHAR(10) ColumnName] 

with result solved the issue

See Source

查看更多
闹够了就滚
6楼-- · 2019-04-05 02:43

Adding @query_result_separator should do the trick.

EXEC sp_send_dbmail @profile_name='default',
@recipients='dev@null.com',
@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

查看更多
登录 后发表回答