SQL Query根据记录号发送电子邮件

时间:2013-10-01 19:02:39

标签: sql sql-server

我有这个SQL查询:

DECLARE @tableHTML  NVARCHAR(MAX) ;

SET @tableHTML =
N'<H1>Table name</H1>' +
N'<table border="1">' +
N'<tr><th>Column name1</th><th>Column name2</th>' +
N'<th>Column name3</th><th>Column name4</th></tr>' +
CAST ( ( select td = login_time, '', 
                td = last_batch, '', 
                td = hostname ,'' ,
                td = loginame, ''
    from master.dbo.sysprocesses
    where loginame<>'sa' and program_name=''
    order by last_batch Desc
          FOR XML PATH('tr'), TYPE 
) AS NVARCHAR(MAX) ) +
N'</table>' ;

EXEC msdb.dbo.sp_send_dbmail 
@profile_name = 'profile name',
@recipients='e-mail account',
@subject = 'e-mail subject',
@body = @tableHTML,
@body_format = 'HTML' ;

但如果有查询记录,我只需要发送电子邮件。

有人可以帮忙???

谢谢。

1 个答案:

答案 0 :(得分:1)

首先检查数据是否存在。像这样:

DECLARE @tableHTML  NVARCHAR(MAX) ;

If Exists(Select 1 from master.dbo.sysprocesses
    where loginame<>'sa' and program_name='')
    Begin

        SET @tableHTML =
        N'<H1>Table name</H1>' +
        N'<table border="1">' +
        N'<tr><th>Column name1</th><th>Column name2</th>' +
        N'<th>Column name3</th><th>Column name4</th></tr>' +
        CAST ( ( select td = login_time, '', 
                        td = last_batch, '', 
                        td = hostname ,'' ,
                        td = loginame, ''
            from master.dbo.sysprocesses
            where loginame<>'sa' and program_name=''
            order by last_batch Desc
                  FOR XML PATH('tr'), TYPE 
        ) AS NVARCHAR(MAX) ) +
        N'</table>' ;

        EXEC msdb.dbo.sp_send_dbmail 
        @profile_name = 'profile name',
        @recipients='e-mail account',
        @subject = 'e-mail subject',
        @body = @tableHTML,
        @body_format = 'HTML' ;
    End