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

时间:2016-05-19 17:15:19

标签: sql-server sp-send-dbmail

我正在尝试让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';

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

如果我必须将Cast作为NVarchar才能使用动态SQL,那么如何在最终电子邮件中将该字段显示为“$ 50.00”?

提前致谢!!

3 个答案:

答案 0 :(得分:1)

而不是td = '$'+ROUND(current1,2), '',这一行,请使用下面的代码来解决您的问题。

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

使用sys.objects表格执行示例,@current1资金数据类型。

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

答案 1 :(得分:1)

使用 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
    ...

答案 2 :(得分:0)

你有正确的想法,但有两个警告:值舍入与格式化和字符串+浮点问题。

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) = $50.00

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

链接:

SQL Fiddle examples

TOTN : ROUND

SO : Concat String and Float