My app is throwing an exception on an "after update" trigger in the database when the following query is run against a record that contains an email address that already exists on another user. In other words, the record hasn't been updated, but should have been ignored because of the EXISTS clause.
Does anybody know why it might be firing the event? Or should the trigger be testing some flag to ensure that it's a real update?
I've tested my code after disabling the trigger and it does exactly as expected so I'm assuming that my query is correct.
An email address can be blank, but otherwise it must be unique in the database. .
The query that's causing this is as follows.
UPDATE users
SET EmailAddress = @emailaddress
WHERE
(
RecID = @recid AND fk_Sites_RecID = @fk_sites_recid
AND
(
/* Allow an update when address is being updated with a blank */
( @emailaddress = '' )
/* Address isn't blank, so test it doesn't exist elsewhere */
OR NOT EXISTS
(
SELECT * FROM users
WHERE
NOT ( RecID = @recid AND fk_Sites_RecID = @fk_sites_recid )
AND RTRIM(LTRIM(COALESCE(EmailAddress,''))) = @emailaddress
)
)
)