从SQL Server为数据集的每一行发送电子邮件

时间:2014-01-20 23:29:05

标签: sql sql-server email sp-send-dbmail dbmail

我已经构建了一个存储过程,用于每周向一组员工发送电子邮件提醒。 SQL Server代理每周运行一个计划过程来构建本周的员工数据集,然后我需要让每个员工收到一封电子邮件,但我不能使用与预定SELECT语句内联的电子邮件存储过程。

这可以使用函数,但我使用EXEC msdb.dbo.sp_send_dbmail发送无法在函数中执行的邮件。

1 个答案:

答案 0 :(得分:7)

使用存储过程。在存储过程内部使用游标来获取电子邮件的详细信息以及您要发送的内容。重复调用sp_send_dbmail,直到所有员工收到电子邮件。

好的,我花了几分钟为您设置测试用例数据库。我们正在向Scott Adams,Dave Letterman和Bill Gates发送电子邮件。

/*  
    Setup test database.
*/

-- Use master
USE [master]
GO

-- Create a simple database using models attributes
CREATE DATABASE [MAIL];
GO

-- Use mail
USE [MAIL]
GO

-- Drop existing
IF OBJECT_ID(N'[DBO].[EMAIL_LIST]') > 0
DROP TABLE [DBO].[EMAIL_LIST]
GO

-- Create new
CREATE TABLE [DBO].[EMAIL_LIST]
(
    ID INT IDENTITY(1,1) PRIMARY KEY,
    EMAIL_ADDRESS VARCHAR(64),
    EMAIL_SUBJ VARCHAR(64),
    EMAIL_BODY VARCHAR(256),
    SENT_FLAG TINYINT DEFAULT (0)
);

-- Insert simple data
INSERT INTO [DBO].[EMAIL_LIST] (EMAIL_ADDRESS, EMAIL_SUBJ, EMAIL_BODY)
VALUES
('scottadams@aol.com','Dilbert','What''s up scott?'),
('lateshow@pipeline.com','Late Show','Please read this letter Dave.'),
('billg@microsoft.com','Gates','How''s the weather in Seatle?');

-- Show the data
SELECT * FROM [DBO].[EMAIL_LIST];

此存储过程会读取未发送电子邮件的电子邮件列表并发送电子邮件。

/*  
    Create stored procedure
*/

-- Drop existing
IF OBJECT_ID(N'[DBO].[SEND_EMAILS]') > 0
DROP PROCEDURE [DBO].[SEND_EMAILS]
GO

-- Create new
CREATE PROCEDURE [dbo].[SEND_EMAILS]
AS
BEGIN

    -- Error handling variables
    DECLARE @err_number int;
    DECLARE @err_line int;
    DECLARE @err_message varchar(2048);
    DECLARE @err_procedure varchar(2048);

    -- ** Error Handling - Start Try **
    BEGIN TRY

    -- No counting of rows
    SET NOCOUNT ON;

    -- Declare variables
    DECLARE @VAR_ADDRESS VARCHAR(64);
    DECLARE @VAR_SUBJ VARCHAR(64);
    DECLARE @VAR_BODY varchar(256);

    -- Get email list
    DECLARE VAR_CURSOR CURSOR FOR
        SELECT EMAIL_ADDRESS, EMAIL_SUBJ, EMAIL_BODY
        FROM [DBO].[EMAIL_LIST] 
        WHERE SENT_FLAG = 0;

    -- Open cursor
    OPEN VAR_CURSOR;

    -- Get first row
    FETCH NEXT FROM VAR_CURSOR 
        INTO @VAR_ADDRESS, @VAR_SUBJ, @VAR_BODY;

    -- While there is data
    WHILE (@@fetch_status = 0)
    BEGIN
        -- Send the email
        EXEC msdb.dbo.sp_send_dbmail 
            @recipients = @VAR_ADDRESS,
            @subject = @VAR_SUBJ,
            @body = @VAR_BODY,
            @body_format = 'HTML' ;  

        -- Grab the next record
        FETCH NEXT FROM VAR_CURSOR 
            INTO @VAR_ADDRESS, @VAR_SUBJ, @VAR_BODY;
    END

    -- Close cursor
    CLOSE VAR_CURSOR;

    -- Release memory
    DEALLOCATE VAR_CURSOR;            

    -- Update the table as processed
    UPDATE [DBO].[EMAIL_LIST] 
    SET SENT_FLAG = 1
    WHERE SENT_FLAG = 0;

    -- ** Error Handling - End Try **
    END TRY

    -- ** Error Handling - Begin Catch **
    BEGIN CATCH

      -- Grab variables 
      SELECT 
          @err_number = ERROR_NUMBER(), 
          @err_procedure = ERROR_PROCEDURE(),
          @err_line = ERROR_LINE(), 
          @err_message = ERROR_MESSAGE();

      -- Raise error
      RAISERROR ('An error occurred within a user transaction. 
                  Error Number        : %d
                  Error Message       : %s  
                  Affected Procedure  : %s
                  Affected Line Number: %d'
                  , 16, 1
                  , @err_number, @err_message, @err_procedure, @err_line);       

    -- ** Error Handling - End Catch **    
    END CATCH                

END

查看MSDB。[dbo]。[sysmail_mailitems]表,我们可以看到这些项目已排队等待。这取决于使用公共默认配置文件设置的数据库邮件。

enter image description here

通过作业安排存储过程取决于您。