SQL使用每个相关数据将db邮件发送给多个收件人

时间:2016-12-19 18:55:59

标签: sql sql-server

我创建了两个存储过程,一个包含数据信息,另一个用于db邮件调用。我有下面第二个存储过程的样本,因为存在问题。

BEGIN
SET NOCOUNT ON;

declare @Coord_ID varchar(20)
declare @Coord_Name varchar(25)
declare @Coord_Email varchar(75)
declare @CoordCursor as cursor
declare @tab char(1) = CHAR(9)
declare @emailBody varchar(100)

declare @sqlCommand varchar(1000) = 'sp_MZ_Get'
declare @qry varchar(1000)

set @CoordCursor = cursor Fast_Forward for
select distinct TARGET_ID, FULL_NAME, Email from vw_Coords where Email <> '' --and Target_ID = '7000001'

open @CoordCursor
fetch next from @CoordCursor into @Coord_ID,@Coord_Name, @Coord_Email
while @@FETCH_STATUS = 0
BEGIN
    Print @Coord_ID + ' ' + @Coord_Email


    set @emailBody = 'Member Renewal Transaction Activity for '+ @Coord_Name

    DECLARE @RenewalActivity TABLE
    (
        Membership_Type varchar(25),
        Member_ID varchar(20),
        Chapter varchar(20),
        Full_Name varchar(35),
        Transaction_Date smalldatetime,
        Renewal_Date smalldatetime,
        AC_ID varchar(10),
        AC_Name varchar(30)
    )

    insert into @RenewalActivity(Membership_Type, Member_ID, Chapter, Full_Name, Transaction_Date, Renewal_Date, AC_ID, AC_Name)
    exec @sqlCommand @Coord_ID

    if OBJECT_ID('tempdb..##temprenewals') is not null
        drop table ##temprenewals

    select * into ##temprenewals from @RenewalActivity

    set @qry = 'select * from ##temprenewals'

    EXEC msdb.dbo.sp_send_dbmail
        @profile_name = 'Admin',
        @recipients = @Coord_Email,
        @query = @qry,
        @execute_query_database = 'TOPS',
        @subject = 'New Members and Renewals',
        @body = @emailBody,
        @attach_query_result_as_file = 1,
        @query_attachment_filename='coord-s-9.csv',
        @query_result_separator=@tab,
        @query_result_no_padding=1

    fetch next from @CoordCursor into @Coord_ID,@Coord_Name, @Coord_Email
END

close @CoordCursor
deallocate @CoordCursor
第一期;收件人收到报告包含所有数据。因为他们应该收到与他们有关的东西 例如:

 Member_ID | Chapter |Coord_Email
 --------------------------------------
 1         |  A05    |  Coord2@Email.com
 5         |  A01    |  Coord1@Email.com
 8         |  A05    |  Coord2@Email.com
 12        |  A01    |  Coord1@Email.com

目前1,5,8和12分去了Coord1和Coord2。意图是5和12与A01相关联转到Coord1,1和8转到Coord2。

第二期; db邮件已成功排队,如日志中所述,有35个收件人。但是,并非所有收件人都包含在邮件中。在90个收件人中,只有35个收到了电子邮件。我检查了第一个查询,结果是所有收件人&#34; 90&#34;。

提前谢谢

0 个答案:

没有答案