使用SQL Server数据库邮件以表格格式发送电子邮件

时间:2019-01-30 08:43:41

标签: sql sql-server stored-procedures ssis

enter image description here

我已经创建了具有1个SQL任务的SSIS程序包(存储过程返回下面4列的列表。如何实现通过电子邮件发送下表。立即执行的下一个任务是创建另一个存储过程,该过程从第一个存储的proc通过另一个Sql任务接受结果集,第二个存储的proc包含msdb_SendDBemail调用,还有没有更好的方法

2 个答案:

答案 0 :(得分:1)

您可以尝试类似的方法以表格格式获取数据。要逐行执行,您需要实现一个这样的游标。

CREATE PROCEDURE [dbo].[SendNewDeviceInfoToEmployee]  

AS  
BEGIN  
SET NOCOUNT ON

DECLARE @Mbody VARCHAR(MAX), 
@Sub VARCHAR(500), 
@EmpEmailPwdId BIGINT, 
@Emp_nm VARCHAR(150), 
@ToEmailid VARCHAR(150), 
@NewEmailId VARCHAR(150), 
DECLARE @Recipients VARCHAR(max)

DECLARE SendautoLoginDtl CURSOR FOR
SELECT EmpEmailPwdId, EmpName, ToEmailid, NewEmailId, EmpPassword 
FROM EmployeeEmailIdPassword WHERE ISNULL(Freeze,'N') = 'N' AND ISNULL(IsMailSent,'N') = 'N' AND ISNULL(ToEmailId,'') <> '' AND ISNULL(NewEmailId,'') <> ''
ORDER BY EmpEmailPwdId

OPEN SendautoLoginDtl;
FETCH NEXT FROM SendautoLoginDtl INTO @EmpEmailPwdId, @emp_nm, @ToEmailid, @NewEmailId
WHILE( @@FETCH_STATUS = 0 )
BEGIN

SET @xml = CAST(( SELECT [Rank] AS 'td','',[Player Name] AS 'td','', [Ranking Points] AS 'td','', Country AS 'td'
FROM #Temp 
ORDER BY Rank 
FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))

SET @Mbody =N'<html><body><H3>Tennis Rankings Info</H3>
        <table border = 1> 
        <tr>
        <th> Rank </th> <th> Player Name </th> <th> Ranking Points </th> <th> Country </th></tr>'    

        SET @body = @body + @xml +'</table></body></html>' 

SET @sub='Your New Device Details - ' + @emp_nm  

set @Recipients =  @ToEmailid 

EXEC msdb.dbo.sp_send_dbmail '<YourDBMailProfileName>' , 
@recipients = @Recipients ,
@copy_recipients = @NewEmailId,
@subject = @sub ,
@body = @Mbody ,  
@body_format = 'HTML'  

--Update table if required
UPDATE <YourTable>
SET IsMailSent = 'Y'
WHERE EmpEmailPwdId = @EmpEmailPwdId

FETCH NEXT FROM SendautoLoginDtl INTO @EmpEmailPwdId, @emp_nm, @ToEmailid, @NewEmailId, @EmpPassword
END

CLOSE SendautoLoginDtl;
DEALLOCATE SendautoLoginDtl;

END

您可以了解光标here

答案 1 :(得分:1)

堆栈交换上的不错线程:Need to Send a formatted HTML Email via Database Mail in Sql Server 2008 R2

它的答案是存储过程dbo.HtmlTable的代码,该代码可以生成HTML以便在数据库邮件中进一步使用:

CREATE table ##foo (bar1 int, bar2 varchar(20), bar3 datetime)
INSERT into ##foo values (1, 'Abcdef', getdate())
INSERT into ##foo values (2, 'Ghijkl', '05/05/15')

DECLARE @tableHtml varchar(max)
EXEC dbo.HtmlTable
    '##foo',
    @tableHtml output
PRINT @tableHtml   

@tableHtml将包含呈现为以下内容的html:

https://i.stack.imgur.com/jc014.jpg