我想在SQL Server中将查询结果作为HTML格式的电子邮件发送。
这是我的代码,
DECLARE @Body varchar(max)
declare @TableHead varchar(max)
declare @TableTail varchar(max)
declare @mailitem_id as int
declare @statusMsg as varchar(max)
declare @Error as varchar(max)
declare @Note as varchar(max)
Set NoCount On;
set @mailitem_id = null
set @statusMsg = null
set @Error = null
set @Note = null
Set @TableTail = '</table></body></html>';
--HTML layout--
Set @TableHead = '<html><head>' +
'<H2 style="color: #000000">Rules changing in 15 Days</H2>' +
'<style>' +
'td {border: solid black 1px;padding-left:5px;padding-right:5px;padding- top:1px;padding-bottom:1px;font-size:9pt;color:Black;} ' +
'</style>' +
'</head>' +
'<body><table cellpadding=0 cellspacing=0 border=0>' +
'<tr bgcolor=#A6A6A6>'+
'<td align=center><b>ID</b></td>' +
'<td align=center><b>Name</b></td>' +
'<td align=center><b>From</b></td>' +
'<td align=center><b>To</b></td></tr>';
--Select information for the Report--
Select @Body= (Select
ID As [ID],
SUBSTRING(Name_List, 2, LEN(Name_List)-2) As [Name],
FromDate as [From],
[ToDate] as [To]
FROM tbl_ProductionDays dm(nolock)
where 1=1
and ToDate between GETDATE() and DATEADD(dd, 15, GETDATE())
For XML raw('tr'), Elements)
-- Replace the entity codes and row numbers
Set @Body = Replace(@Body, '_x0020_', space(1))
Set @Body = Replace(@Body, '_x003D_', '=')
Set @Body = Replace(@Body, '<tr><TRRow>1</TRRow>', '<tr bgcolor=#C6CFFF>')
Set @Body = Replace(@Body, '<TRRow>0</TRRow>', '')
Set @Body = @TableHead + @Body + @TableTail
-- return output--
--Email
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'SqlDBMAIL',
@recipients='abc@gmail.com',
@subject = 'notification email',
@body = @Body,
@body_format = 'HTML';
但是此代码不会以适当的格式发送电子邮件。每行仅显示在ID列中。
如何以正确的格式显示?
答案 0 :(得分:0)
您已在表格单元格中添加了列标题,但您需要对列数据执行相同的操作。
将SELECT更改为类似的内容应该这样做:
Select @Body= (Select
'<td>'+ID+'</td>' As [ID],
'<td>'+SUBSTRING(Name_List, 2, LEN(Name_List)-2)+'</td>' As [Name],
'<td>'+FromDate+'</td>' as [From],
'<td>'+[ToDate]+'</td>' as [To]
FROM tbl_ProductionDays dm(nolock)
where 1=1
and ToDate between GETDATE() and DATEADD(dd, 15, GETDATE())
For XML raw('tr'), Elements)