1

我在从 SQL Server 发送 HTML 格式的电子邮件时遇到问题。

使用以下代码部分,我得到一个"Line 1, incorrect syntax near '<'"错误。

SET @tableHTML =
    '<H1>Progress Report</H1>' +
    '<table border="1">' +
    '<tr>' +
                '<th>Project Name</th>' +
                '<th>Platform</th>' +
                '<th>Due By</th>' +
                '<th>Current Status</th>' +
                '<th>Current State</th>' +
    '</tr>' +
    CAST (  
                ( 
                        SELECT
                                td = [Project Name],    ' ',
                                td = Platform,  ' ',
                                td = [Due By],  ' ',
                                td = [Current Status],  ' ',
                                td = [Current State],   ' '
    FROM [dbo].[table_name]
    ORDER BY [Current Status] DESC
    FOR XML PATH('tr'), TYPE
              ) AS NVARCHAR(MAX) ) +
    '</table>' ;

我似乎无法将它固定在任何特别的东西上?有任何想法吗?

谢谢

更新1:

好的,我在调试会话中运行了代码并检查了@tableHTML 的内容,内容看起来很好,并且填充了我的表中的预期数据。

意味着来自其他地方的错误,所以这次我复制了整个查询。

DECLARE @tableHTML NVARCHAR(MAX);

SET @tableHTML =
    '<h1>Progress Report</h1>' +
    '<table border="1">' +
    '<tr>' +
                '<th>Project Name</th>' +
                '<th>Platform</th>' +
                '<th>Due By</th>' +
                '<th>Current Status</th>' +
                '<th>Current State</th>' +
    '</tr>' +
    CAST 
        (   
                ( 
                        SELECT
                                td = [Project Name],    '',
                                td = Platform,  '',
                                td = [Due By],  '',
                                td = [Current Status],  '',
                                td = [Current State],   ''
    FROM [dbo].[table_name]
    ORDER BY [Current Status] DESC
    FOR XML PATH('tr'), TYPE
              ) AS NVARCHAR(MAX) ) +
    '</table>';

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'db_mail_account',
    @recipients = 'example@example.com',
    @subject = 'Daily Project Tracking Report',
    @query = @tableHTML,
    @body_format = 'HTML';

再次感谢。

4

1 回答 1

0

看起来您想@tableHTML成为电子邮件的正文,但您将其作为 传递@query,其中必须包含有效的 SQL,因此出现错误。

尝试@body改用:

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'db_mail_account',
    @recipients = 'example@example.com',
    @subject = 'Daily Project Tracking Report',
    @body = @tableHTML,
    @body_format = 'HTML';
于 2015-03-11T11:39:46.363 回答