Saturday, 7 March 2015

sp_send_dbmail with HTML grid example

DECLARE @tableHTMLbegin  NVARCHAR(MAX) ;

    SET @tableHTMLbegin =
        N'<H2 style="font-family:Sans-serif;color:black;font-size:15px;">Test Report</H2>' +
        N'<table border="0.5" width ="25%" bgcolor="white" style="font-family:arial;color:black;font-size:10px;">' +
        N'<th align="center" width ="25%" bgcolor="#C0C0C0" style="font-family:arial;color:black;font-size:10px;">Date</th>
              <th align="center" width ="20%" bgcolor="#C0C0C0" style="font-family:arial;color:black;font-size:10px;">  Period  </th>
              <th align="center" width ="20%" bgcolor="#C0C0C0" style="font-family:arial;color:black;font-size:10px;">   Column1</th>
              <th align="center" width ="20%" bgcolor="#C0C0C0" style="font-family:arial;color:black;font-size:10px;">  Column2  </th>
              <th align="center" width ="20%" bgcolor="#C0C0C0" style="font-family:arial;color:black;font-size:10px;">  Column3  </th>                  
              </tr><center>
              ' + +
        CAST ( ( SELECT case when MatchFlag='N' then '#F79F81' else '#BEF781' end AS [@bgcolor] ,  td=isnull(Date,GETDATE()), '' ,
                          td=isnull(Period,''), '' ,
                          td=isnull(Column1,'-'), '' ,
                          td=isnull(Column2,'-'), '' ,
                          td =isnull(MatchFlag,'_'), ''
                 FROM [TEST].dbo.TestTable
                 order by Date,Period
                  FOR XML PATH('tr'), TYPE
        ) AS NVARCHAR(MAX) ) +
        N'</center></table><br><hr><img src="test_small.png" border="0" width="100" height="60" />' ;

set @tableHTMLbegin = isnull(@tableHTMLbegin,'<H2 style="font-family:arial;color:#009999;font-size:20px;">Test Report</H2><hr><img src="test_small.png" border="0" width="120" height="60" /></a><H2 style="font-family:arial;color:black;font-size:15px;">There are no recent periods '+ convert(varchar(12),getdate(),103) +'</H2><br>')

declare @v_errorcount int,
            @v_subject nvarchar(200)

select @v_errorcount = count(*)
from [TEST].dbo.TestTable
where MatchFlag = 'N'

 set @v_subject = 'Test Report - a date has been flagged'

declare @v_attachments nvarchar(200)   
set @v_attachments    =N'D:\Test\test_small.png'
EXEC msdb.dbo.sp_send_dbmail @recipients='Shane.Ryan@gmail.com;',
    @profile_name = 'Test_DB_Mail',
    @subject = @v_subject ,
    @body = @tableHTMLbegin ,
    @body_format = 'HTML',
    @file_attachments = @v_attachments;

--background color changes when a column is flagged

No comments:

Post a Comment