Run sql job with different email addresses from sql table

DBA9 21 Reputation points
2021-06-08T08:44:39.467+00:00

Hello,
I have a sql table with recipient email addresses along with unique id, names etc.. How would I run a sql job to send HTML formatted email (includes table data) to different recipients from a table.

It should start from row 1 until it reaches the last row.

Please let me know how to execute sql job with different emails.

Thank you

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
14,320 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,676 questions
{count} votes

Accepted answer
  1. Olaf Helper 45,626 Reputation points
    2021-06-08T09:41:00.137+00:00

    You can use a cursor to process all email addresses, create the email content and send it.
    Little example:

    DECLARE @email varchar(200);
    DECLARE email CURSOR FOR  
        SELECT emailAddress
        FROM yourTable;
    
    OPEN email;
    FETCH NEXT FROM email INTO @email;
    WHILE @@FETCH_STATUS = 0  
    BEGIN  
        PRINT @email
        -- EXEC sp_send_dbmail ....
        FETCH NEXT FROM email INTO @email;
    END;
    
    CLOSE email;  
    DEALLOCATE email;
    
    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Cris Zhan-MSFT 6,641 Reputation points
    2021-06-09T07:24:16.48+00:00

    Hi,

    Through the combination of cursor, variables and the stored procedure sp_send_dbmail to traverse the mail address in the table and send mails to them in turn, Olaf gives a good example.

    Specify the argument @Tomas Podoba _format in sp_send_dbmail to send message body in HTML format.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.