为什么我会在关键字'FOR'附近找到“语法不正确”?

时间:2012-01-04 19:20:50

标签: sql-server-2008 triggers

我有两张表personcustomer。从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'.

为什么不能读取每一行?

2 个答案:

答案 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)