简体   繁体   English

如何以CSV格式发送查询结果?

[英]How to send a query result in CSV format?

I am working on ETL and I have this below sql code in my SQL Task in SSIS package.我正在研究 ETL,我在 SSIS 包中的 SQL 任务中有以下 sql 代码。 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.我希望以 CSV 格式发送此附件。 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.提前致谢。

Adding @query_result_separator should do the trick.添加@query_result_separator应该可以解决问题。

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.添加@query_result_no_padding = 1可能会@query_result_no_padding = 1清理结果。 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;

Adding添加

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

with result solved the issue结果解决了这个问题

See Source查看来源

This comment on purple frog indicates you can also use the tab character as a delimiter: 这条关于紫色青蛙的评论表明您还可以使用制表符作为分隔符:

 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

Also looks like this answer's been posted already, my bad: https://stackoverflow.com/a/44315682/5758637看起来这个答案已经发布了,我的错: https : //stackoverflow.com/a/44315682/5758637

Inside a proc:在一个过程中:

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

with a normal hard return within the column alias after "sep=,".在“sep=,”之后的列别名内有一个正常的硬回车。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM