The way that I typically do this is to put these results into the @body
parameter, and not the @query
parameter. That is, I first get all of the results and format them, and then simply pass that to the procedure, instead of doing it on the fly at the procedure call.
This might look something like this:
DECLARE @EmailBody NVARCHAR(MAX) = 'Some Text Here <table><thead><tr><th>SomeHeaderOne</th><th>SomeHeaderTwo</th></tr></thead><tbody>##TableBody##</tbody>'
DECLARE @EmailTableContent NVARCHAR(MAX)
SELECT @EmailTableContent = COALESCE(@EmailTableContent + '', '')
+ '<tr>'
+ '<td style="border-bottom: solid 1px #ddd; padding: 20px;">' + ColumnOne + '</td>'
+ '<td style="border-bottom: solid 1px #ddd; padding: 20px; text-align: center;">' + ColumnTwo + '</td>'
+ '</tr>'
FROM TheTable
WHERE ColumnOne = 'Something'
SELECT @EmailBody = REPLACE(@EmailBody, '##TableBody##', @EmailTableContent)
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Database Email',
@recipients = 'dbcheck@xxx.com',
@subject = 'SQL Replication Deletion Check',
@body = @EmailBody,