Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Your trigger is an "AFTER" trigger (the default) rather than "INSTEAD OF". With an AFTER trigger, the "deed has been done" already--i.e., the insert into DeletedUser has already occurred, so you do <em>not</em> need the INSERT statement.</p> <p>The foreign key relationship between DeletedUser and UserLogin is just all wrong. These tables are, from what you have described, <em>mutually exclusive</em>: having a user in DeletedUser means they should no longer be in UserLogin, and having the user in UserLogin means they wouldn't also be a DeletedUser.</p> <p>So, remove the foreign key relationship, and try this:</p> <pre><code>CREATE TRIGGER trgInsert_ToDeleteFromUserLogin on DELETEDUSER FOR INSERT AS BEGIN DELETE FROM UserLogin WHERE EXISTS (SELECT NULL FROM INSERTED WHERE INSERTED.USERNAME = UserLogin.USERNAME) END </code></pre> <p>Edit: As Shannon mentioned below, this code will properly handle situations where multiple records are inserted at the same time, in contrast to the single-row assumption of the original code. The use case (disabling a user) suggested only a single insert at a time, but it's better (and easier) to built triggers to operate against the entire set of records in the inserted/deleted metatables.</p> <p>As an aside, your database design could be simplified by using views. Example:</p> <pre><code>ALTER TABLE UserLogin ADD DeletedReason varchar(255) NULL CREATE VIEW ActiveUser AS SELECT * FROM UserLogin WHERE DeletedReason IS NULL </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload