我有一张表,其中包含一个票务所有者列表以及分配给它们的优先票据。
例如:
我需要使用sp_send_dbmail从sql server发送邮件到John,并在一封邮件中分配给他的所有票证。这是一个巨大的表格,因此我希望通过单个邮件向用户发送邮件,而不是每张邮件发送一封邮件。 任何帮助将不胜感激。
答案 0 :(得分:0)
答案 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
;