Using sp_send_dbmail with recieptent and content from single sql row

走远了吗. 提交于 2019-12-04 04:58:07

问题


I have a table filled with oldUserID, newUserID, name and email. I want to use sp_send_dbmail to the email on each row. For example:

oldUserID | newUserID | name | email

21213125 | 2355233571 | Tom | tom@gmail.com

65465465 | 4564884664 | Mat | mat@gmail.com

And so on for 200 rows. Is there any way to send an sp_send_dbmail to the email on each row including oldUserID and newUserID? The output in the mail would be something like:

"Your old user id: 21213125, your new user id: 2355233571"

I would appreciate not to enter each emailadress manually.

Thank you!


回答1:


DECLARE
      @txt NVARCHAR(MAX)
    , @name NVARCHAR(60)
    , @email VARCHAR(100)

DECLARE cur CURSOR FAST_FORWARD READ_ONLY LOCAL FOR
    SELECT 'Your old user id: ' + CAST(oldUserID AS NVARCHAR(100)) 
         + ', your new user id: ' + CAST(newUserID AS NVARCHAR(100)), name, email
    FROM ...

OPEN cur

FETCH NEXT FROM cur INTO @txt, @name, @email

    WHILE @@fetch_status = 0
    BEGIN

        EXEC msdb.dbo.sp_send_dbmail @profile_name = ...
                                   , @recipients = @email
                                   , @subject = @name
                                   , @body = @txt
                                   , @body_format = 'HTML'

    FETCH NEXT FROM cur INTO @txt, @name, @email

    END

CLOSE cur
DEALLOCATE cur


来源:https://stackoverflow.com/questions/37279577/using-sp-send-dbmail-with-recieptent-and-content-from-single-sql-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!