SQL 服务器 2008 R2 - sp_send_dbmail

SQL Server 2008 R2 - sp_send_dbmail

一开始我标记 - 我不是编写代码的专家。我需要你的帮助。我想通过 sp_send_dbmail.

实现电子邮件通知系统

代码:

USE msdb
go

SET QUOTED_IDENTIFIER OFF
SET ANSI_NULLS ON

EXEC sp_send_dbmail @profile_name='PROFILENAME',
    @recipients='myemail@email.com',
    @query_result_header=0,
    @attach_query_result_as_file=0,
    @query="select Kod,Nazwa from DATABASE.dbo.Towar where Kod NOT LIKE '%?%' and (AsId=205 or AsId=304 or AsId=289 or AsId=321 or AsId=306 or AsId=217 or AsId=261) and Aktywny=1 ORDER BY Kod",
    @body_format="text",
    @subject='SUBCJECT'
GO

SQL 查询有效并发送电子邮件,但也发送空行。例如。如何摆脱它们?

1916                 SER TWAROGOWY WIEJSKI LUZ                                                                                                                                                                                                                  

我也想sp_send_dbmail只在查询returns数据时发送邮件。如果没有数据 - 不发送消息。

我认为你需要 IF,如果你想要有条件的电子邮件:

IF EXISTS (select Kod, Nazwa from DATABASE.dbo.Towar where Kod NOT LIKE '%?%' and AsId IN (205, 304, 289, 321, 306, 217, 261) and Aktywny = 1)
BEGIN
    EXEC sp_send_dbmail @profile_name='PROFILENAME',
        @recipients='myemail@email.com',
        @query_result_header=0,
        @attach_query_result_as_file=0,
        @query='select Kod, Nazwa from DATABASE.dbo.Towar where Kod NOT LIKE ''%?%'' and AsId IN (205, 304, 289, 321, 306, 217, 261) and Aktywny=1 ORDER BY Kod',
        @body_format='text',
        @subject='SUBCJECT';
END;

GO