如果插入的记录符合某些条件,我需要在SQL表中创建一个触发器来发送电子邮件。 也就是说,我在表1中创建触发器,如果在插入的记录中,则向X发送电子邮件,字段IdCircuito = 53,IdTipoDoc = 45,Gestor ='Gest1'。此外,在电子邮件正文中,我希望显示该插入记录的某个字段的值。我做过类似的事情,但无论插入的记录如何,触发器总是执行:
CREATE TRIGGER dbo.SendEmail
ON dbo.TitulosDoc
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
IF EXISTS (SELECT 1 FROM TitulosDoc WHERE IdCircuito = 53 AND IdTipoDoc = 45 AND Gestor = 'Gest1')
BEGIN
EXEC msdb.dbo.sp_send_dbmail
@recipients = 'rsg@gmail.com',
@subject = 'New requeriment',
@body = 'It's a new requeriment: ';
END
END
GO
在body中我想要显示带有插入记录字段值的文字文本: @body ='这是一个新的requeriment:'+ TitulosDoc.NombreDocumento;
有人能帮助我吗?谢谢
答案 0 :(得分:1)
要访问插入的行,您需要从INSERTED
中进行选择。
试试这个:
CREATE TRIGGER dbo.SendEmail
ON dbo.TitulosDoc
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @NombreDocumento VARCHAR(MAX) = (SELECT INSERTED.NombreDocumento
FROM INSERTED
WHERE INSERTED.IdCircuito = 53
AND INSERTED.IdTipoDoc = 45
AND INSERTED.Gestor = 'Gest1')
IF @NombreDocumento IS NOT NULL
BEGIN
EXEC msdb.dbo.sp_send_dbmail
@recipients = 'rsg@gmail.com',
@subject = 'New requeriment',
@body = 'It''s a new requeriment: ' + @NombreDocumento;
END
END
GO
答案 1 :(得分:0)
我会做Sean Lange所说的...创建一个名为TempTitulosDoc的物理表,然后将您的记录插入需要通过电子邮件发送的记录。在触发器中执行此操作。
CREATE TRIGGER dbo.SendEmail
ON dbo.TitulosDoc
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
BEGIN
INSERT INTO TempTiulosDoc(field1, field2, EmailStatus)
SELECT field1, field2, 0 AS EmailStatus --Email NOT sent
FROM TitulosDoc
WHERE IdCircuito = 53 AND IdTipoDoc = 45 AND Gestor = 'Gest1'
END
END
GO
创建一个这样的存储过程,循环遍历这些记录并发送电子邮件。完成后,更新TempTitlosDoc,状态为1表示已发送的电子邮件。
DECLARE @loopCount INT
DECLARE @field1 VARCHAR(10)
DECLARE @field2 VARCHAR(10)
DECLARE @EmailStatus int
--Create Temp Table
CREATE TABLE #Temp
(
id int not null identity,
field1 VARCHAR(10),
field2 VARCHAR(10),
EmailStatus int
)
--Insert Tasks to temp table
INSERT INTO #Temp (field1, field2, EmailStatus)
SELECT field1, field2, EmailStatus
FROM dbo.TempTiulosDoc
WHERE Status = 0
--Set a loopCount for while loop
SET @loopCount = 1
--Use the while loop to check if we have any Tasks left to send
while ( exists(SELECT id FROM #Temp WHERE id = @loopCount) )
BEGIN
--Get current record in temp table
SELECT @field1 = field1,
@field2 = field2,
@EmailStatus = EmailStatus
FROM #Temp
WHERE id = @loopCount
EXEC msdb.dbo.sp_send_dbmail
@recipients = 'rsg@gmail.com',
@subject = 'New requeriment',
@body = 'It''s a new requeriment: ' + @NombreDocumento;
--Update your work table with the status of 1 so it's not picked up again
UPDATE teq
SET teq.@EmailStatus = 1
FROM dbo.TempTiulosDoc teq
WHERE teq.id = @field1
SET @loopCount = @loopCount + 1
END