如何为MS SQL Server编写this触发器?
MySql版本:
CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
WHERE patron_info.pid = old.id;
END
Sql server版本:
CREATE TRIGGER log_patron_delete ON patrons AFTER DELETE
AS
BEGIN
DELETE FROM patron_info WHERE patron_info.pid = old.id;
END
问题:old.id
适用于MySql,但不适用于MS SQL Server
答案 0 :(得分:1)
这不是触发器的工作,它是外键约束的工作。
您应该在patrons
表和patron_info
表之间创建一个外键,并使用选项delete cascade
创建它。
ALTER TABLE patron_info
ADD CONSTRAINT FK_patron_info_patrons FOREIGN KEY (pid)
REFERENCES patrons(id)
ON DELETE CASCADE
这样,你不能在patron_info中有任何与patrons表无关的行,一旦你从patrons表中删除了一行,patron_info中的相应行就会被自动删除。