问题
My question is same as in question heading and below is the code what I have tried.
ALTER TRIGGER [dbo].[Entrega_Insert]
ON [dbo].[Entrega]
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
DECLARE @DataEntrega DATETIME, @IdEncomenda INT, @QTDEncomenda INT
DECLARE @IdVisita INT
SELECT @DataEntrega = DataEntrega, @IdEncomenda = b.IdEncomenda
FROM [dbo].[Entrega] AS a
INNER JOIN [dbo].[Encomenda] AS b ON a.[IdEncomenda] = b.[IdEncomenda]
INNER JOIN [dbo].[Visita] AS c ON b.[IdVisita] = c.[IdVisita]
--INNER JOIN
DECLARE @BigBody VARCHAR(500) = CAST(@DataEntrega AS VARCHAR(100)) + ' ' + CAST(@IdEncomenda AS VARCHAR(100))
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Dc'
,@recipients = 'danny17kx@gmail.com'
,@subject = 'A sua encomenda foi processada e aceite.'
,@body = @BigBody
,@importance ='HIGH'
,@body_format='HTML'
END
回答1:
This is too long for a comment.
I would strongly discourage your from attempting to send email through a trigger. Just the fact that you don't even know to use inserted
suggests that you are not familiar enough with how SQL works. You are going to be locking the table (or part of it) while the email is attempted.
What can you do? The simplest is to write a stored procedure to send email and do the insert at the same time. This gives you more control over email failures.
The more "professional" solution would probably involve message queues. You would do the insert, then insert a message into a queue. At the other end, a listener would send the email and handle any issues with email failures.
回答2:
You got the wrong values because your query is targeting the main table without any filtering, so you'll get a random values from the table.
You should use inserted
table instead, which will store the last inserted values.
so your query should be like this :
SELECT TOP 1 @DataEntrega = DataEntrega, @IdEncomenda=b.IdEncomenda
FROM inserted AS a
INNER JOIN [dbo].[Encomenda] AS b ON a.[IdEncomenda]= b.[IdEncomenda]
INNER JOIN [dbo].[Visita] AS c ON b.[IdVisita] = c.[IdVisita]
Not sure if the INNER JOINs are useful here, but if IdEncomenda is already defined in Entrega
table, then I think you'll be better off these joins.
Remember your method will only get one row, so if you insert multiple rows, you won't get all of them via email. So, you'll need to use other methods such as XML
, COALESCE
, or STUFF
to concrete the results into @BigBody.
来源:https://stackoverflow.com/questions/54263896/send-an-email-with-trigger-when-i-got-the-email-the-values-were-wrong