查询使用相应的票证向mutliple用户发送邮件

时间:2016-02-05 12:15:24

标签: sql-server-2008-r2

我有一张表,其中包含一个票务所有者列表以及分配给它们的优先票据。

例如:

enter image description here

我需要使用sp_send_dbmail从sql server发送邮件到John,并在一封邮件中分配给他的所有票证。这是一个巨大的表格,因此我希望通过单个邮件向用户发送邮件,而不是每张邮件发送一封邮件。 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

非常快速的Google搜索会为您提供所需的所有信息:

https://msdn.microsoft.com/en-gb/library/ms190307.aspx

此页面准确告诉您需要了解的内容。

答案 1 :(得分:0)

这应该可以解决问题......

SET NOCOUNT ON;

--sample of your tickets table
CREATE TABLE #Tickets(
    TicketId INT IDENTITY, 
    TicketOwner VARCHAR(100),
    TicketDetails VARCHAR(MAX)
    )
;

--some sample values
INSERT INTO #Tickets(
    TicketOwner, 
    TicketDetails
    ) 
VALUES
    ('John', 'This is the first ticket'), 
    ('John', 'This is the second ticket'), 
    ('Jeremy', 'This is the third ticket')
;

--gets the dense_rank so you can iterate through the list of distinct users
SELECT  
     TicketId, 
     TicketOwner, 
     TicketDetails, 
     DENSE_RANK() OVER (ORDER BY TicketOwner) AS RowNum
INTO #Temp
FROM #Tickets
ORDER BY TicketOwner, TicketId
;

--holds the details of each email
DECLARE 
    @RowNum INT = (SELECT MAX(RowNum) FROM #Temp),
    @MySubject VARCHAR(100) = '',
    @MyBody VARCHAR(MAX) = ''
;

--iterate through distinct TicketOwnders by using the dense rank value above
WHILE @RowNum > 0
BEGIN
    --assign variables
    SELECT  @MySubject = TicketOwner + '''s tickets:',
            @MyBody = @MyBody + 'Ticket #' + CAST(TicketId AS VARCHAR(10)) + ': ' + TicketDetails + CHAR(10) + CHAR(13)
    FROM #Temp
    WHERE RowNum = @RowNum
    ;

    --send mail
    EXEC msdb.dbo.sp_send_dbmail
        @recipients = 'jgiaco@fanatics.com',
        @subject = @MySubject,
        @body = @MyBody
    ;

    SET @RowNum = @RowNum - 1;
    SET @MyBody = '';
    SET @MySubject = '';
END
;