How can I use sp_send_dbmail to send multiple queries?

chama picture chama · Jan 26, 2011 · Viewed 8.6k times · Source

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!

Answer

Kenny Evitt picture Kenny Evitt · Jan 26, 2011

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 = '[email protected]',
    @subject = 'SQL Server Database Mail · Job step logs',
    @body = @cat,
    @body_format = 'HTML',
    @mailitem_id = @email_id OUTPUT