通过存储过程发送电子邮件失败

时间:2014-07-14 10:05:38

标签: tsql stored-procedures sql-server-2008-r2

DECLARE 
    @id nvarchar(MAX),
    @Counter int,
    @CheckCount int

DECLARE CC1 CURSOR READ_ONLY
FOR
    SELECT Ename, Ecount
    FROM TestDB.dbo.TestEmail

OPEN CC1

FETCH NEXT FROM CC1 INTO @id, @Counter

WHILE @@FETCH_STATUS = 0
BEGIN
    Begin
    EXEC msdb.dbo.sp_send_dbmail
         @profile_name = 'Bob',
         @recipients = @id,
         @body = 'The stored procedure finished successfully. #$%',
         @subject = 'Automated Success Message' ;

    update TestDB.dbo.TestEmail 
    set Ecount = Ecount + 1 
    where Ename = @id 

    print @id
END

Select 
    @CheckCount = Ecount 
from TestDB.dbo.TestEmail 
where Ename = @id

print @CheckCount

If @CheckCount > 3
Begin
    exec msdb.dbo.sp_update_job @job_id = N'6a81d6b3-af2d-4a27-b688-b9c69098f840', @enabled = 0
    return
    PRINT 'Count reached 3+'
End 

FETCH NEXT FROM CC1 INTO @id, @Counter
END

CLOSE CC1
DEALLOCATE CC1

我有一个表TestEmail,其中包含两列Ename, Ecount。通过使用此表,我正在尝试向用户发送电子邮件。如果Ecount大于3,则脚本退出,并且没有任何反应。

一位用户只会收到三次电子邮件。但我的功能失败了,无法弄清楚我哪里出错了。我的脚本不会抛出任何错误,但也不起作用。

1 个答案:

答案 0 :(得分:0)

Marc的编辑为我工作。我写这个问题的时候,我不知道TSQL编程。 虽然,我的问题中的代码工作正常,这是一个很棒的教程,通过SQl服务器发送电子邮件。

Send email in SQL server