我设置了一个触发器以插入到表中,然后希望安排一个代理作业以从所述表发送电子邮件。我有触发器工作,我认为我让 SP 可以正常发送电子邮件,但我的循环卡住并在我取消 SP 之前发送了数百封电子邮件。对我做错了什么有任何想法吗?我使用BatchEmailID
作为标志来知道需要发送什么以及不需要发送什么,'0' = 它没有被发送并且需要去并且'1' = 它已经被发送所以忽略。
创建表:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[tb_BatchEmail](
[BatchEmailID] [bit] NULL,
[To] [varchar](50) NULL,
[Body] [varchar](255) NULL,
[Subject] [varchar](20) NULL,
[Profile] [varchar](50) NULL,
[OrderID] [varchar](25) NULL,
[OrderDateTime] [datetime] NULL,
[SentDateTime] [datetime] NULL
) ON [PRIMARY]
GO
插入值:
INSERT INTO tb_BatchEmail
VALUES (
'0'
,'someemail@address.com'
,'msg body'
,'Test Subject'
,'dbmail profile'
,'123456.001'
,'6/4/2015'
,NULL
),
(
'0'
,'someemail@address.com'
,'msg body'
,'Test Subject'
,'dbmail profile'
,'123456.002'
,'6/4/2015'
,NULL
)
sp_send_dbmail:
while 1=1
begin
declare @BatchEmailID bit
declare @To varchar (25)
declare @Body varchar (250)
declare @Subject varchar (25)
declare @ProfileName varchar (20)
select top 1
@BatchEmailID = BatchEmailID,
@To = [To],
@Body = Body,
@Subject = [Subject],
@ProfileName = [Profile]
from tb_BatchEmail
where BatchEmailID = 0
if(@BatchEmailID is null)
break;
EXEC msdb.dbo.sp_send_dbmail @recipients = @To
,@body = @Body
,@subject = @Subject
,@profile_name = @ProfileName
update tb_BatchEmail
set BatchEmailID = 1, SentDateTime = GETDATE()
where BatchEmailID = @BatchEmailID
end