从MySql到Sql Server的删除触发器之后进行转换

时间:2016-04-13 14:26:17

标签: mysql sql-server

如何为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

1 个答案:

答案 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中的相应行就会被自动删除。