“删除”触发器不起作用,而“添加”触发器正常工作。
它应该像这样工作:“当我删除得分表中具有subject_id = 1且得分> 8的记录时,exellentEng在类表中将为-1” 我不知道为什么帮帮我
ALTER TRIGGER [dbo].[deleteExellentEnglishStudent]
ON [dbo].[dbo_score]
AFTER DELETE AS
BEGIN
UPDATE x SET
exellent_Eng -=1
FROM dbo.dbo_class x
JOIN dbo.dbo_student s ON s.class_id = x.class_id
JOIN dbo.dbo_score c ON c.student_id = s.student_id
WHERE (c.subject_id = 1 AND c.score >= 8)
and c.score_id in (SELECT Deleted.score_id FROM Deleted)
END
ALTER TRIGGER [dbo].[addExellentEnglishStudent] ON [dbo].[dbo_score]
AFTER INSERT AS
BEGIN
UPDATE x SET
exellent_Eng += 1
FROM dbo.dbo_class x
JOIN dbo.dbo_student s ON s.class_id = x.class_id
JOIN dbo.dbo_score c ON c.student_id = s.student_id
WHERE (c.subject_id = 1 AND c.score >= 8)
AND c.score_id IN
(select Inserted.score_id from Inserted)
END
答案 0 :(得分:2)
该行在dbo_score
表中将不存在,因为它是一个after
触发器,因此该行已被删除。而是直接使用Deleted
伪表,例如
ALTER TRIGGER [dbo].[deleteExellentEnglishStudent]
ON [dbo].[dbo_score]
AFTER DELETE AS
BEGIN
UPDATE x SET
exellent_Eng -=1
FROM dbo.dbo_class x
JOIN dbo.dbo_student s ON s.class_id = x.class_id
JOIN dbo.Deleted c ON c.student_id = s.student_id
WHERE (c.subject_id = 1 AND c.score >= 8)
END
注意:正如我在另一个问题上说的那样,如果触发器每次都绝对地计算值,而不是进行求和,则可能会更容易编写和维护这些触发器。然后您可以使用相同的逻辑进行插入,更新和删除,例如像这样:
ALTER TRIGGER [dbo].[deleteExellentEnglishStudent]
ON [dbo].[dbo_score]
AFTER INSERT, UPDATE, DELETE
AS
BEGIN
UPDATE x SET
exellent_Eng = (select count(*) from dbo.dbo_score where c.subject_id = 1 AND c.score >= 8)
FROM dbo.dbo_class x
JOIN dbo.dbo_student s ON s.class_id = x.class_id
where S.studentid in (select student_id from Inserted union all select student_id from Deleted)
END