我有两张表person
和customer
。从person
中删除时,我要从customer
删除
CREATE TRIGGER DELCUS
ON Person
AFTER DELETE
FOR EACH ROW
begin
DELETE FROM customer
WHERE customer.PersonID_Fk=Person.PersonId;
end
这是我得到的错误:
Msg 156, Level 15, State 1, Procedure DELCUS, Line 5
Incorrect syntax near the keyword 'FOR'.
为什么不能读取每一行?
答案 0 :(得分:3)
如果您使用的是SQL Server,则需要:
CREATE TRIGGER DELCUS
ON Person
AFTER DELETE AS
begin
DELETE c
FROM customer
WHERE EXISTS (select 1 from deleted where customer.PersonID_Fk=deleted.PersonId);
end
如果您使用的是MySQL,那就是:
CREATE TRIGGER DELCUS
ON Person
AFTER DELETE AS
begin
DELETE c
FROM customer
WHERE EXISTS (select 1 from old where customer.PersonID_Fk=old.PersonId);
end
但实际上,如果您确实设置了FK,那么当您尝试删除某个人的参考失败时,它会出错。最好的办法是将你的FK设置为on delete cascade
。
答案 1 :(得分:1)
或者您可以使用:
DELETE FROM customer
WHERE customer.PersonID_Fk in (select personid from deleted)