【问题标题】:sp_send_dbmail attachment encodingsp_send_dbmail 附件编码
【发布时间】:2023-09-22 20:20:01
【问题描述】:

我正在使用 SQL2005 中的 sp_send_dbmail 发送一封电子邮件,其中包含附件中的结果。发送附件时,它是 UCS-2 编码的,我希望它是 ANSI 或 UTF-8。

这里是 SQL

EXEC msdb.dbo.sp_send_dbmail
    @recipients = 'temp@example.com'
    , @query = 'DECLARE @string_to_trim varchar(60);SET @string_to_trim = ''1234''; select rtrim(@string_to_trim), ''tom'''
    , @query_result_header=0
    , @subject = 'see attach'
    , @body= 'temp body'
    , @profile_name= N'wksql01tAdmin'
    , @body_format = 'HTML'
    ,@query_result_separator = ','
    ,@query_attachment_filename = 'results.csv'
    ,@query_no_truncate = '0'
    ,@attach_query_result_as_file = 1

我在网上看到一些cmets用sql2005 SP2解决了这个问题,但发现不是这样。

【问题讨论】:

    标签: sp-send-dbmail


    【解决方案1】:

    经过对 SQL Server 2008 R2 的一些研究:

    1. 添加到sp_send_dbmail:

      @ANSI_Attachment BIT = 0
      WITH EXECUTE AS 'dbo'
      
    2. 替换

      IF(@AttachmentsExist = 1)
          BEGIN
      .......
          END
      

      与:

      IF(@AttachmentsExist = 1)
      BEGIN
          if (@ANSI_Attachment = 1) 
          begin
              --Copy temp attachments to sysmail_attachments      
              INSERT INTO sysmail_attachments(mailitem_id, filename, filesize, attachment)
              SELECT @mailitem_id, filename, filesize, 
                      convert(varbinary(max), 
                          substring( -- remove BOM mark from unicode
                              convert(varchar(max), CONVERT (nvarchar(max), attachment)), 
                              2, DATALENGTH(attachment)/2
                          )
                      )
      
              FROM sysmail_attachments_transfer
              WHERE uid = @temp_table_uid
          end else begin
              --Copy temp attachments to sysmail_attachments      
              INSERT INTO sysmail_attachments(mailitem_id, filename, filesize, attachment)
              SELECT @mailitem_id, filename, filesize, attachment
              FROM sysmail_attachments_transfer
              WHERE uid = @temp_table_uid
          end
      END
      

    【讨论】:

    • 这似乎可以解决问题!该文件现在是 ANSI 编码的,可以在 Excel 中很好地打开。
    • 作为参考,这也适用于 SQL Server 2005(谢谢@Gena!)。我最终创建了一个新的 proc sp_send_dbmail2,希望能更明显地表明它不是标准的。
    • 非常棒。谢谢。
    • 高五是您在 * 上给出的唯一答案!像魅力一样工作!
    【解决方案2】:

    我认为解决您所看到的问题的唯一方法是使用 BCP 将数据转储到平面文件,然后附加该文件。抱歉,我无法提供更多帮助。 :(

    【讨论】:

      【解决方案3】:

      为了使文件为 ANSI/UTF-8

      使用此行以及其他变量更改位于msdb 中的 sp_send_dbmail:@ANSI_Attachment BIT = 0

      @mailitem_id INT = NULL OUTPUT,
           @ANSI_Attachment BIT = 0
           WITH EXECUTE AS 'dbo'
      

      然后将此行添加到您对 sp_send_dbmail 的调用中:

      @ansi_attachment = 1
      

      那么它应该给你一个 ansi 附件而不是 unicode。

      【讨论】: