0

我有这个 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' ;

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

有人可以帮忙吗???

谢谢你。

4

1 回答 1

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
于 2013-10-01T19:06:06.690 回答