如何为sql结果集

时间:2016-01-06 14:29:23

标签: sql-server sql-server-2012

我有一个名为EMails的SQL Server表,其中包含列

  
      
  • Id int,
  •   
  • 主题nvarchar(100)
  •   
  • Body nvarchar(MAX),
  •   
  • 收件人nvarchar(100)
  •   
  • IsSent位   

我的应用程序填充它。

我想使用SQL Server发送电子邮件。

我知道如何发送电子邮件

EXEC msdb.dbo.sp_send_dbmail

然而查询

SELECT Subject,Body,Recipient FROM EMails
WHERE IsSent=0

最多可以返回多个

我还希望在邮件发送后将IsSent设置为1

问题:

  1. 是否可以使用预定的SQL Server作业。如果是这样,你能提供代码示例吗?

  2. 当查询被放入每15分钟运行一次的SQL Server作业时,建议最多发送50封电子邮件

1 个答案:

答案 0 :(得分:3)

DECLARE @Subject NVARCHAR(100),
        @Body NVARCHAR(MAX),
        @Recipient NVARCHAR(100),
        @ID INT,
        @MailID INT

DECLARE @mails TABLE (ID INT, MailID INT)

DECLARE cur CURSOR FAST_FORWARD READ_ONLY LOCAL FOR
    SELECT ID, [Subject], Body, Recipient
    FROM dbo.EMails
    WHERE IsSent = 0

OPEN cur

FETCH NEXT FROM cur INTO @ID, @Subject, @Body, @Recipient

WHILE @@FETCH_STATUS = 0 BEGIN

    EXEC msdb.dbo.sp_send_dbmail
        @profile_name = '....',
        @recipients   = @Recipient,
        @subject      = @Subject,
        @body         = @Body,
        @mailitem_id  = @MailID OUTPUT

    INSERT INTO @mails (ID, MailID)
    VALUES (@ID, @MailID)

    FETCH NEXT FROM cur INTO @ID, @Subject, @Body, @Recipient

END

CLOSE cur
DEALLOCATE cur

WAITFOR DELAY '00:00:01'

UPDATE u
SET IsSent = 1
FROM dbo.EMails u
JOIN @mails m ON u.ID = m.ID
JOIN msdb.dbo.sysmail_mailitems s ON m.MailID = s.mailitem_id
WHERE s.sent_status = 1

-- failed mails

SELECT s.recipients, s.[subject], s.body, s.sent_status
FROM @mails m
JOIN msdb.dbo.sysmail_mailitems s ON m.MailID = s.mailitem_id
WHERE s.sent_status != 1