Mit sp_send_dbmail lassen sich Abfrageergebnisse nicht nur als Text senden, sondern mit etwas XML und HTML als formatierte Tabelle.
Der Schlüssel ist die Klausel FOR XML PATH. Sie erzeugt pro Zeile ein <tr>-Element und pro Spalte ein <td>-Element.
Beispiel
DECLARE @body_content nvarchar(max);
SET @body_content = N'
<style>
table.GeneratedTable {
width: 100%;
background-color: #ffffff;
border-collapse: collapse;
border-width: 2px;
border-color: #ffcc00;
border-style: solid;
color: #000000;
}
table.GeneratedTable td,
table.GeneratedTable th {
border-width: 2px;
border-color: #ffcc00;
border-style: solid;
padding: 3px;
}
table.GeneratedTable thead {
background-color: #ffcc00;
}
</style>
<table class="GeneratedTable">
<thead>
<tr>
<th>ArtistId</th>
<th>ArtistName</th>
<th>ActiveFrom</th>
</tr>
</thead>
<tbody>' +
CAST((
SELECT td = ArtistId, '',
td = ArtistName, '',
td = ActiveFrom, ''
FROM Music.dbo.Artists
FOR XML PATH('tr'), TYPE
) AS nvarchar(max)) + N'</tbody>
</table>';
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'DB Admin Profile',
@recipients = 'example@sqldat.com',
@body = @body_content,
@body_format = 'HTML',
@subject = 'As discussed';
Der gesamte Inhalt wird in @body_content zusammengesetzt und dann an @body übergeben. Das CSS sorgt für sichtbare Rahmen, eine farbige Kopfzeile und etwas Innenabstand. Ohne CSS können Sie den <style>-Block und class="GeneratedTable" weglassen.
Wichtig: @body_format = 'HTML' muss gesetzt sein. Andernfalls sehen Empfänger den Markup-Code statt einer gerenderten Tabelle.