格式化来自 SQL Server 2008 的 HTML 电子邮件中的查询数据

Formatting query data in HTML email from SQL Server 2008

我正在尝试让 SQL Server 2008 发送 HTML 格式的电子邮件,但是我在查询中提取的字段之一是 "money" 数据类型,因此显示小数点后 3 位数字,但我似乎无法显示美元符号。这是我目前所拥有的:

DECLARE @BodyText NVARCHAR(MAX);

SET @BodyText =
N'Please notify the attorney of the direct pay(s) shown below:<BR><BR>' +
N'<table border="1">' +
N'<tr><th>File</th><th>Name</th><th>Balance</th><th>Atty File</th>' +
CAST ( ( SELECT td = number,    '',
                td = Name,  '',
                td = '$'+ROUND(current1,2), '',
                td = CC.AttorneyAccountID,  ''
from master 
    inner join CourtCases CC on master.number = CC.AccountID
where number = 1234567
          FOR XML PATH('tr'), TYPE 
) AS NVARCHAR(MAX) ) +
N'</table>' ;


--Notify legal team of legal DPs
exec msdb.dbo.sp_send_dbmail 
@profile_name = 'Default'
, @recipients = 'me@mycompany.com'
, @subject = 'test html email'
, @Body = @BodyText
, @body_format = 'HTML';

问题出在主 table 的 "current1" 字段上。即使使用上面的代码,该字段仍然显示为“50.000”。

如果我必须将 Cast 设置为 NVarchar 才能使用动态 SQL,我如何才能使该字段在最后一封电子邮件中显示为“$50.00”?

提前致谢!!

代替td = '$'+ROUND(current1,2), '',这一行,请使用下面这行它会解决你的问题。

td = CONCAT('$', ROUND(current1, 2)), '',

使用 sys.objects table 和 @current1 作为 Money 数据类型的示例执行。

DECLARE @BodyText NVARCHAR(MAX);
DECLARE @current1 AS Money = '50.000';

SET @BodyText =
N'Please notify the attorney of the direct pay(s) shown below:<BR><BR>' +
N'<table border="1">' +
N'<tr><th>File</th><th>Name</th><th>Balance</th><th>Atty File</th>' +
CAST ( ( SELECT td = [type_desc],    '',
                td = Name,  '',
                td = CONCAT('$', ROUND(@current1, 2)), '',
                td = [type],  ''
          FROM SYS.objects 
          WHERE [type] = 'U' 
          FOR XML PATH('tr'), TYPE 
) AS NVARCHAR(MAX) ) +
N'</table>' ;

--PRINT @BodyText

使用SQL Server 2012及更高版本,您可以使用FORMAT函数获取带有货币符号的值。在你的情况下是这样的

SELECT 
    ...
    td = FORMAT(current1, 'C', 'en-us')
FROM
    ...

对于 SQL Server 2008,您可以这样实现 -

SELECT 
    ...
    td = '$'+CAST(CAST(current1 AS DECIMAL(10, 2)) AS VARCHAR)
FROM
    ...

您的想法是正确的,但有两个注意事项:值舍入与格式化以及 String+Float 问题。

Round() 接受数值表达式并使用 length 参数来确定 numeric_expression 的四舍五入精度。

值是四舍五入的,但格式不是。

例如:

ROUND(current1 , -1) = 50.000

您的值有 3 位小数。如果您希望反映不同的小数位数,则必须将您的值转换为具有该长度的小数,即

CAST(current1 AS DECIMAL(10, 2)) = 50.00

现在是字符串串联的用武之地。这个值仍然是一个浮点数,不能与字符串组合。这是您需要转换为 Varchar 并与 '$'

连接的地方
'$'+CAST(CAST(current1 AS DECIMAL(10, 2)) AS VARCHAR) = .00

此解决方案适用于 Sql Server 2008。

链接:

SQL Fiddle examples

TOTN : ROUND

SO : Concat String and Float