I need to create a trigger of some sort that will delete an event record from my events table when the related records in my signedUp table all have a viewed field set to 1.
events
----------
eventID
eventName
eventLocation
signedUp
----------
signedID
eventID
empID
viewed
The viewed field defaults to 0 but gets set to 1 for a user when they view a message pertaining to the event, once all users have viewed the message all of their flags will be set to 1 and at that point I want to delete the related record from the events table, how can I create a trigger to do this?
Create TRIGGER [dbo].[<tr_name>]
ON [dbo].[signedUp]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
if exists(select s.eventID from signedUp s
inner join inserted i on i.eventid = s.eventid
group by s.eventID
having count(s.eventID) = SUM(s.viewed))
delete e from events e inner join inserted i on i.eventid = e.eventid
END
Try this:
CREATE OR REPLACE TRIGGER signedup_sau -- statement after update
AFTER UPDATE ON signedup
DELETE FROM events
WHERE NOT EXISTS (SELECT 1
FROM signedup
WHERE signedup.eventid = events.eventid
AND signedup.viewed != 1);
END;
The trigger has to run after the entire UPDATE
statement runs, as it is neither possible nor logical to reference the same table in a row level trigger.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.