仅在结果可用时发送sp_send_dbmail

时间:2018-03-23 19:12:15

标签: sql sql-server email email-integration

我只想在执行的查询输出且不为空时才从我的数据库发送电子邮件。 我想知道如何做到这一点以及将其嵌入到我的代码中的位置。在我的头顶,我想到计算结果并计算> 0或者与查询结合使用@@ rowcount>你会建议什么? 这是我的代码:

ALTER proc dbo.spBornBefore2000 as
set nocount on 
DECLARE @sub VARCHAR(100),
 @qry VARCHAR(max),
 @msg VARCHAR(250),
 @query NVARCHAR(max),
 @tab char(1) = CHAR(9)

SELECT @sub = 'before 1990 -' + cast(getdate() as varchar(100)) 
SELECT @msg = N'blablabla.....'
SELECT @query = ' select id, name, dob, year(dob) as birth_year 
                     from people
                     where year(dob) < 2000  '

EXEC msdb.dbo.sp_send_dbmail
            @profile_name = 'USERS',
            @recipients =  'abc@gmail.com',
            @body = @msg,
            @subject = @sub,
            @query = @query,
            @query_attachment_filename = 'before2000.csv',
            @attach_query_result_as_file = 1,
            @query_result_header = 1,
            @query_result_width = 256 ,
            @query_result_separator = @tab,
            @query_result_no_padding =1;

2 个答案:

答案 0 :(得分:0)

您可以这样做:

EXEC(@query) IF @@ ROWCOUNT&gt; 0     开始          - 在这里发送电子邮件     END

答案 1 :(得分:0)

  ALTER proc dbo.spBornBefore2000 as
    set nocount on 
    DECLARE @sub VARCHAR(100),
     @qry VARCHAR(max),
     @msg VARCHAR(250),
     @query NVARCHAR(max),
     @tab char(1) = CHAR(9)

    SELECT @sub = 'before 1990 -' + cast(getdate() as varchar(100)) 
    SELECT @msg = N'blablabla.....'
    SET @query = ' select id, name, dob, year(dob) as birth_year 
                         from people
                         where year(dob) < 2000  '

    IF EXISTS (select id, name, dob, year(dob) as birth_year 
                         from people
                         where year(dob) < 2000)
        begin

            EXEC msdb.dbo.sp_send_dbmail
                        @profile_name = 'USERS',
                        @recipients =  'abc@gmail.com',
                        @body = @msg,
                        @subject = @sub,
                        @query = @query,
                        @query_attachment_filename = 'before2000.csv',
                        @attach_query_result_as_file = 1,
                        @query_result_header = 1,
                        @query_result_width = 256 ,
                        @query_result_separator = @tab,
                        @query_result_no_padding =1;
        end
    ELSE
        begin
        EXEC msdb.dbo.sp_send_dbmail
                        @profile_name = 'USERS',
                        @recipients =  'myself@gmail.com',
                        @body = 'No results returned'
        end