How can I use sp_send_dbmail to send multiple queries?

家住魔仙堡 提交于 2019-12-01 17:57:46

Use the @query parameter of the stored procedure msdb.dbo.sp_send_dbmail for the attachment and use the @body parameter with a variable that contains the result of the other query.

The example code below creates a string from SQL Server job step history that contains HTML table elements used to send an email using the stored procedure msdb.dbo.sp_send_dbmail. You should be able to adapt it for your purposes.

DECLARE @cat        varchar(MAX),
        @email_id   int


SELECT @cat = COALESCE(@cat + '', '')
                + '<tr><td>'
                + j.[name] + '</td><td>'
                + CAST(js.step_id AS varchar) + '</td><td>'
                + js.step_name + '</td><td>'
                + CONVERT(char(23), jsl.date_created, 121) + '</td><td>'
                + jsl.[log] + '</td></tr>'
FROM    msdb.dbo.sysjobstepslogs jsl
        JOIN msdb.dbo.sysjobsteps js ON jsl.step_uid = js.step_uid
        JOIN msdb.dbo.sysjobs j ON js.job_id = j.job_id


SET @cat = '
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<style type="text/css">
    td {
        border: 1pt dotted #ddd;
    }

    #log_text {
        width: 20em;
    }
</style>
</head>
<body>
<table>
<colgroup>
    <col />
    <col />
    <col />
    <col />
    <col id="log_text" />
</colgroup>
<thead>
<tr>
<th>Job</th><th>Step</th><th>Step name</th><th>Log created</th><th>Log text</th></tr>
</thead>
<tbody>
        ' + @cat + '
</tbody>
</table>
</body>
</html>'


EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'SQLServerDatabaseMailProfile',
    @recipients = 'person@example.com',
    @subject = 'SQL Server Database Mail · Job step logs',
    @body = @cat,
    @body_format = 'HTML',
    @mailitem_id = @email_id OUTPUT
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!