我尝试按如下方式创建触发器:
CREATE OR REPLACE TRIGGER update_student
AFTER UPDATE OF school ON student FOR EACH ROW
BEGIN
UPDATE school SET num2=num2+1 WHERE school.id=(SELECT school FROM inserted);
END;
/
但是当我执行代码时,它显示Trigger created with compilation errors
,然后执行show errors;
,它显示如下:
2/5 PL/SQL: SQL Statement ignored
2/71 PL/SQL: ORA-00942: table or view does not exist
我想这里的表格意味着学校,但我确信表school
存在。问题出在哪里?请帮我一把。谢谢!
我修改了代码如下:
CREATE OR REPLACE TRIGGER update_student
AFTER UPDATE OF school ON student FOR EACH ROW
BEGIN
UPDATE :new.school SET num2=num2+1 WHERE school.id=(SELECT :new.school FROM inserted);
END;
/
但是发生了新的错误。它显示:
2/5 PL/SQL: SQL Statement ignored
2/24 PL/SQL: ORA-00903: invalid table name
我该如何解决?谢谢!
答案 0 :(得分:0)
在触发器中,您应该使用:NEW和:OLD伪行来访问新旧字段值。因此,您的UPDATE语句应为:
UPDATE school
SET num2 = num2 + 1
WHERE school.id = :NEW.SCHOOL;
您可能还想减少旧学校的学生人数:
UPDATE SCHOOL
SET NUM2 = NUM2 - 1
WHERE SCHOOL.ID = :OLD.SCHOOL;
如果STUDENT.SCHOOL(旧版本或新版本)为NULL,您应该避免尝试更新SCHOOL行:
CREATE OR REPLACE TRIGGER UPDATE_STUDENT
AFTER UPDATE OF SCHOOL ON STUDENT
FOR EACH ROW
BEGIN
IF :NEW.SCHOOL IS NOT NULL THEN
UPDATE SCHOOL
SET NUM2 = NUM2 + 1
WHERE SCHOOL.ID = :NEW.SCHOOL;
END IF;
IF :OLD.SCHOOL IS NOT NULL THEN
UPDATE SCHOOL
SET NUM2 = NUM2 - 1
WHERE SCHOOL.ID = :OLD.SCHOOL;
END IF;
END UPDATE_STUDENT;
祝你好运。