将mysql触发器转换为pl / sql触发器

时间:2016-01-09 12:35:05

标签: mysql oracle plsql oracle-apex

我之前已经为我的mysql项目创建了一个触发器,它运行良好。但是,我试图更改此触发器以使其适合pl-sql(oracle)。这是我在mysql中使用的原始代码:

DELIMITER $$
CREATE TRIGGER course_title_delete AFTER DELETE on Course
FOR EACH ROW
BEGIN
DECLARE rownumber INT;
SET rownumber = (SELECT COUNT(*) FROM Course 
    WHERE Course_code=old.Course_code);
IF rownumber = 0
THEN
DELETE FROM Course_title
    WHERE Course_title.Course_code=old.Course_code;
    END IF;
END$$
DELIMITER ;

这个是我尝试转换pl-sql格式的代码。但是,当我作为脚本上传并尝试在顶点运行时,它无法正常工作。

CREATE OR REPLACE TRIGGER course_title_delete 
AFTER DELETE ON course
FOR EACH ROW
BEGIN
DECLARE rownumber INT;
SET rownumber = (SELECT COUNT(*) FROM course 
    WHERE course_code= :old.course_code);
IF rownumber = 0
THEN
DELETE FROM course_title
    WHERE course_title.course_code:=:old.course_code;
    END IF;
END;
/ 

1 个答案:

答案 0 :(得分:1)

至少,您在此行中有语法错误:

DELETE FROM course_title
    WHERE course_title.course_code:=:old.course_code;
----------------------------------^

那应该是=

此外,在Oracle中,DECLAREBEGIN之前,而不在之后。

另外,在Oracle中,这一行:

SET rownumber = (SELECT COUNT(*) FROM course 
   WHERE course_code= :old.course_code);

应该是:

SELECT COUNT(*) INTO rownumber 
FROM course
WHERE course_code = :old.course_code;

嗯,实际上,这是你所表达的正确语法。但是,您应该在两个数据库中使用NOT EXISTS而不是COUNT(*)

在两个数据库中,我认为您可以使用级联删除外键约束替换此触发器。此外,您可以简化逻辑以消除if

CREATE OR REPLACE TRIGGER course_title_delete 
AFTER DELETE ON course
FOR EACH ROW
BEGIN
    DELETE FROM course_title
    WHERE NOT ExISTS (SELECT 1
                      FROM course c
                      WHERE c.course_code = :old.course_code
                     ) AND
          course_code = :old.course_code;
END;