How can I use sp_send_dbmail to send multiple queries?

若如初见. 提交于 2019-12-19 19:40:23

问题


I'm trying to send an email using sp_send_dbmail. I need it to send one query as an attachment and another as part of the body of the email. The problem is that sp_send_dbmail only has one @query parameter, and I can't see any way to add another one.

Is there any way to either a) add a second query (with all of the parameters attached to it) or b) execute the query into a variable and then add that to the body of my email?

I'm using sql-server 2005.

TIA!


回答1:


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


来源:https://stackoverflow.com/questions/4808340/how-can-i-use-sp-send-dbmail-to-send-multiple-queries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!