如何使用带有SQL的sp_send_dbmail存储过程将查询结果作为csv发送电子邮件?
我想发送一封包含查询结果的电子邮件作为csv附件 到目前为止,我有这个如何使用带有SQL的sp_send_dbmail存储过程将查询结果作为csv发送电子邮件?,sql,sql-server,tsql,csv,stored-procedures,Sql,Sql Server,Tsql,Csv,Stored Procedures,我想发送一封包含查询结果的电子邮件作为csv附件 到目前为止,我有这个 EXEC msdb.dbo.sp_send_dbmail @recipients='me@myself.com', @subject='CSV Extract', @profile_name = 'Valid profile', @body='See attachment', @query ='SELECT TOP 10 c.* FROM MyDb.dbo.Customers c',
EXEC msdb.dbo.sp_send_dbmail
@recipients='me@myself.com',
@subject='CSV Extract',
@profile_name = 'Valid profile',
@body='See attachment',
@query ='SELECT TOP 10 c.* FROM MyDb.dbo.Customers c',
@attach_query_result_as_file = 1,
@query_attachment_filename = 'CSV_Extract.csv',
@query_result_separator = ','
我收到带有csv附件的电子邮件,但在Excel中打开时,结果的格式糟糕透了(例如,所有值都在一列中,似乎有随机缩进)
我应该怎么做才能得到格式正确、列标题正确的结果
编辑
我已将以下参数添加到查询中
@query_result_width = 32767,
@query_result_no_padding = 1
这改进了很多,但是当在Excel中打开时,我仍然将每条记录放在一列中。如何将记录中的每个值放入它自己的列中
这是我目前得到的
这就是我想要的
问题在于Excel不理解列。要解决此问题,您需要向Excel发送说明,解释csv文件 指令必须在数据之前是文件的第一部分,因此您必须为查询中包含Excel指令以及所需实际名称的第一个字段创建别名 指令为“sep=,”,以确保excel理解逗号字段分隔符
DECLARE @column1name varchar(50)
-- Create the column name with the instrucation in a variable
SET @Column1Name = '[sep=,' + CHAR(13) + CHAR(10) + 'Name]'
DECLARE @qry varchar(8000)
-- Create the query, concatenating the column name as an alias
SELECT @qry='set nocount on; SELECT TOP 10 c.CCustName ' + @column1name +
' ,c.CID Id FROM MyDb.dbo.Customers c'
EXEC msdb.dbo.sp_send_dbmail
@recipients='me@myself.com',
@subject='CSV Extract',
@profile_name = 'Valid Profile',
@body='See attachment',
@query =@qry,
@attach_query_result_as_file = 1,
@query_attachment_filename = 'CSV_Extract.csv',
@query_result_separator = ',',
@query_result_width = 32767,
@query_result_no_padding = 1
这些是最终结果
它并不完美(第二行很烦人),但对于我来说,它确实足够好了因为您所需要的格式只有您自己知道,请尝试使用以下值
@query\u result\u separator=',',@query\u result\u width=32767,@query\u result\u no\u padding=1
,包括查询字符串中的“set nocount;”去掉(2行受影响)“我的结果中的行”