SQL 电子邮件格式消失 CR LF

SQL Email Formatting disappearing CR LF

我有一个选择数据并生成电子邮件的 TSQL 脚本。 我的脚本相当复杂,但我已将其简化为一个简单的示例来演示我的问题。

简单来说,当我的一个字段超过特定长度(21 个字符)时,我插入到 VAR_Body 变量中的 CR 和 LF 就会丢失。字段中的文本未被分类运行。

预期结果

Renewal Date= 23 Jun 2017
Existing Insurer= 1234567890123456789012
Existing Insurer ID= 6007

实际结果

Renewal Date= 23 Jun 2017
Existing Insurer= 1234567890123456789012 Existing Insurer ID= 6007

如果我从 Existing Insurer 字符串中提取一个字符,它就会起作用。

这是我用来演示问题的简化代码。

有人知道这里发生了什么吗?

我 运行 没有东西可以尝试。

谢谢

大卫

-- Email Variables
Declare @VAR_Dest_EmailAddress varchar(150)
set @VAR_Dest_EmailAddress = 'myemail@email.com.au'
Declare @VAR_Subject varchar(100)
Declare @VAR_Body  varchar(1000)

-- Format Variables
Declare @DateDisplayFormat int
Set @DateDisplayFormat = 106 -- DD MMM YYYY eg 25 MAY 2017
Declare @MoneyDisplayFormat int
set @MoneyDisplayFormat = 1  -- Commas every three digits and two digits to the right of the decimal point.


-- Data variables
Declare @sPlanNumber varchar(10)
Declare @dRenewal datetime
Declare @sExistingInsurer varchar(50)
Declare @lExistingInsurerID int

-- Set the Variables
Set @sPlanNumber = '12345'
Set @dRenewal = '2017-06-23 00:00:00.000'
set @sExistingInsurer = '1234567890123456789012'
set @lExistingInsurerID = '6007'

-- Set the body of the email
    set @VAR_Body = 'Renewal Date= ' + Convert(varchar(11),@dRenewal,@DateDisplayFormat) + CHAR(13)+ CHAR(10) 
    set @VAR_Body = @VAR_Body + 'Existing Insurer= ' + @sExistingInsurer + CHAR(13) + CHAR(10)
    set @VAR_Body = @VAR_Body + 'Existing Insurer ID= ' + Convert(varchar(10),@lExistingInsurerID) + CHAR(13) + CHAR(10)

-- Send the email
EXEC msdb.dbo.sp_send_dbmail 
    @recipients = @VAR_Dest_EmailAddress,
    @subject = @sPlanNumber,
    @body = @VAR_BODY,
    @profile_name = 'SQL Email Profile' ;

如果您对电子邮件格式没有要求(TEXT 与 HTML),您可以对电子邮件使用 HTML 格式。然后,您可以使用 <br/> 和其他 html 标签来格式化电子邮件。

EXEC msdb.dbo.sp_send_dbmail 
    @recipients = @VAR_Dest_EmailAddress,
    @subject = @sPlanNumber,
    @body = @VAR_BODY,
    @body_format = 'HTML' --declare the body formatting of the email to be HTML
    @profile_name = 'SQL Email Profile' ;

然后您可以格式化您的电子邮件:

set @VAR_Body = 'Renewal Date= ' + Convert(varchar(11),@dRenewal,@DateDisplayFormat) + '<br/>' 
--we can now use the html break character which will be rendered by all email clients
set @VAR_Body = @VAR_Body + 'Existing Insurer= ' + @sExistingInsurer + '<br/>'
set @VAR_Body = @VAR_Body + 'Existing Insurer ID= ' + Convert(varchar(10),@lExistingInsurerID) + '<br/>'

可以在 MSDN 文档中找到参考 here