I have the following trigger:
BEGIN
DECLARE @email varchar(200)
DECLARE @jobcode int
DECLARE @status char(1)
DECLARE @emaild varchar(200)
DECLARE @jobcoded int
DECLARE @statusd char(1)
SET @statusd = NULL
SELECT @status = z.status, @email = p.EMail, @jobcode = z.jobID
FROM zipoutfiles z
INNER JOIN inserted AS i ON z.jobID = i.jobID
INNER JOIN PS_LoginUser AS p ON z.UserID = p.UserID
SELECT @statusd = z.status, @emaild = p.EMail, @jobcoded = z.jobID
FROM zipoutfiles z
INNER JOIN deleted AS d ON z.jobID = d.jobID
INNER JOIN PS_LoginUser AS p ON z.UserID = p.UserID
WHERE d.jobID = @jobcode
IF ((@status = 'D' AND @statusd = 'R') OR (@status = 'D' AND @statusd = 'E'))
BEGIN
EXEC SendMail @email, @jobcode
END
END
I want to be able to run SendMail when status goes from E to D or R to D, but not D to D (if it gets updated again) and also when it gets inserted as D. What am I doing wrong here:
Not sure what your table schemas are, but this may get you all of the appropriate emails:
I’ve assumed that you aren’t really updating
JobId. If so, how do you match the before and after rows?Also assumed is that
Statuscannot beNULL. If so, the last condition needs to be modified to properly detect no corresponding row was found in thedeletedtable.