首页 > 解决方案 > 使用 dbmail sp 打印整个表

问题描述

我正在尝试在邮件正文中打印表格结果,但是当它被执行时,只有一行结果在邮件中获取和打印。

输出应以表格形式打印,整个表格结果应在邮件正文中。

SELECT 
	@str1 =
	COALESCE(@str1 + ' ', '') +
	--'<tr><td align="right">' + CONVERT(NVARCHAR(30), CURRENT_DTM, 109) + '</td>' +
	'<td align="right">' + ISNULL(CONVERT(NVARCHAR(30), MIN_START_DTM, 109), 0) + '</td>' +
	'<td align="right">' + ISNULL(CONVERT(NVARCHAR(30), MAX_END_DTM, 109), 0) + '</td>' +
	'<td align="left">' + SERVER + '</td>' +
	--'<td align="left">' +  + '</td>' +
	'<td align="right">' + CONVERT(NVARCHAR(20), REPLACE(CONVERT(VARCHAR, CONVERT(MONEY, TXN_CNT_LAST_HR), 1), '.00', '')) + '</td>' +
	'<td align="right">' + CONVERT(NVARCHAR(20), REPLACE(CONVERT(VARCHAR, CONVERT(MONEY, AVG_RESPONSE_LAST_HR), 1), '.00', '')) + '</td>' +
	'<td align="right">' + ISNULL(CONVERT(NVARCHAR(20), TXN_Less_2_SEC), 0) + '</td>' +
	'<td align="right">' + ISNULL(CONVERT(NVARCHAR(20), TXN_GRTR_5_SEC), 0) + '</td>' +
	'<td align="right">' + ISNULL(CONVERT(NVARCHAR(20), TXN_GR_2sec_LS_5_SEC), 0) + '</td></tr> '
FROM ##Report
ORDER BY  SERVER,TXN_CNT_LAST_HR
  
SET @str1 = ISNULL(@str1, '<tr>No records to show</tr>')

SET @rpt =
N'<table>' +
N'<table border = 1>' +
N'<tr><th colspan=5>Txn = Transaction, Resp = Response Time</th><th colspan=3>Txn count with Resp more than</th></tr>' +
N'<th>Min Timestamp</th>' +
N'<th>Max Timestamp</th>' +
N'<th>Server</th>' +
N'<th >Txn Count</th>' +
N'<th>Avg Resp (seconds)</th>' +
N'<th>2 sec</th>' +
N'<th>5 sec</th>' +
N'<th>2 to 5 sec</th></tr>' +
@str1 + 
N'</table>'

EXEC msdb.dbo.sp_send_dbmail	@profile_name='MainMail',
								@recipients = 'mspatewar007@gmail.com'
								,@subject = 'Report'
								,@body = @rpt
								,@body_format = 'HTML'

标签: sql-serverhtml-tablesp-send-dbmail

解决方案


也许您只需要在字符串中附加一个 CTRL/LF。测试一下,看看它是否有效。

DECLARE @T TABLE(ID NVARCHAR(25))
INSERT @T VALUES('A'),('B'),('C'),('D')

DECLARE @HTML1 NVARCHAR(MAX)  = ''-- <-- Set this to empty string to avoid concatenation a string with a null equals null
DECLARE @HTML2 NVARCHAR(MAX)  = ''-- <-- Set this to empty string to avoid concatenation a string with a null equals null

SELECT 
    @HTML1 = @HTML1 + ISNULL(ID+ ':)' + CHAR(13) + CHAR(10),''), -- <-- Embed a CTRL/LF
    @HTML2 = @HTML2 + ISNULL(ID+ ':)','')
FROM @T

PRINT @HTML1
PRINT @HTML2

推荐阅读