使用dbmail sp打印整个表

时间:2019-04-29 11:02:35

标签: sql-server html-table sp-send-dbmail

我正在尝试在邮件正文中打印表结果,但是当执行表结果时,只有一行结果是在邮件中提取并打印。

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

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'

1 个答案:

答案 0 :(得分:0)

也许您只需要在字符串中附加一个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