发送两个表结果为SQL SERVER 2008的html电子邮件正文

时间:2013-09-18 21:02:01

标签: sql-server-2008 html-email

我已经能够通过创建包含sql查询结果和发送定期电子邮件的表来生成报告。我现在需要将它们中的一些合并为一个并且很难​​让它工作。单个表可以工作,但是两个表会生成一封空白电子邮件。

 DECLARE @TITLE NVARCHAR(MAX)
 DECLARE @BODY NVARCHAR(MAX)
 DECLARE @TITLE2 NVARCHAR(MAX)
 DECLARE @BODY2 NVARCHAR(MAX)
 DECLARE @SECTABLE NVARCHAR(MAX)

 SET @TITLE =CAST((SELECT DISTINCT A.CLIENTPROJ as 'td','', A.CLIENTKEY as 'td','', 
 A.APIBOX   as 'td','', A.ID as 'td', '', 
 COUNT(B.QUERYTERMS) as 'td', ''
 FROM Clients AS A INNER JOIN QueryData AS B ON A.clientKey = B.clientKey 
 WHERE A.Id='0001000'
  group by A.clientProj, A.clientkey, A.APIBox, A.ID order by 
 COUNT(B.QUERYTERMS) desc
 FOR XML PATH ('tr'), ELEMENTS XSINIL) AS NVARCHAR(MAX))

 SET @BODY = '<html><body><H4>QUERY ACTIVITY</H4>
 <H5>CLIENT ID - 0001000</H5>
 <table border = 2>
 <tr>
 <th> CLIENT NAME </th> <th> CLIENT KEY </th> <th> API FEED </th> 
 <th> CLIENT ID </th> <th> TOTAL QUERIES </th></tr>'

 SET @BODY = @BODY + @TITLE + '</TABLE></BODY></HTML>' 
EXEC msdb.dbo.sp_send_dbmail @profile_name='ME Admin',
  @recipients = 'YAHOO@WOOHOO.com',
  @subject = 'CLIENT QUERY REPORT',
  @body =   @BODY,
  @body_format = 'HTML';

不确定如何以及在何处包含以下第二个查询:

  SET @TITLE2 =CAST((SELECT DISTINCT B.CLIENTPROJ as 'td','', 
  B.CLIENTKEY as 'td','', B.apiBOX as 'td','', B.ID as 'td', '', 
  COUNT(A.QUERYTERMS) as 'td', ''
  FROM QUERYDATA AS A RIGHT JOIN CLIENTS AS B ON 
  A.clientKey = B.clientKey WHERE A.Id='0001000' AND A.clientKey 
   IS NULL
  group by B.clientProj, B.clientkey, B.APIBox, B.ID order by 
  COUNT(A.QUERYTERMS) desc
  FOR XML PATH ('tr'), ELEMENTS XSINIL) AS NVARCHAR(MAX))

  SET @BODY2 = '<html><body><H4>QUERY INACTIVITY</H4>
  <H5>CLIENT ID - 0001000</H5>
  <table border = 2>
   <tr>
  <th> CLIENT NAME </th> <th> CLIENT KEY </th> <th> API FEED</th> 
  <th>CLIENT ID </th> <th> TOTAL QUERIES </th></tr>'

我需要两个表格出现在电子邮件的正文中,我不知道如何整合这个。任何想法都赞赏。

1 个答案:

答案 0 :(得分:0)

最终设定声明     SET @TITLE = ....     SET @BODY ='查询活动                  ....'

SET @TITLE2 = ...//SECOND TABLE CONTENTS
SET @BODY2 =  '<html><body><H4>QUERY INACTIVITY</H4>
               <H5>....</tr>'
SET @BODY2 = @BODY + @BODY2 + @TITLE2 + '</TABLE></BODY></HTML>'