我需要创建一种类型的触发器,当我的signedUp表中的相关记录都将被查看的字段设置为1时,将从我的事件表中删除事件记录。
events
----------
eventID
eventName
eventLocation
signedUp
----------
signedID
eventID
empID
viewed
查看字段默认为0,但当用户查看与事件有关的消息时,将其设置为1,一旦所有用户查看了该消息,他们的所有标志都将设置为1,此时我想要从事件表中删除相关记录,如何创建触发器来执行此操作?
答案 0 :(得分:1)
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
答案 1 :(得分:1)
试试这个:
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;
触发器必须在整个UPDATE
语句运行后运行,因为在行级触发器中引用同一个表既不可能也不合理。