简体   繁体   English

Oracle SQL触发器插入/更新

[英]Oracle SQL Trigger insert/update

Ok so my question should be an easy one i think. 好的,所以我的问题应该很简单。 I am just learning Triggers, and I am trying to figure out a homework question. 我只是在学习触发器,并且试图解决一个家庭作业问题。 I have three tables, Movies (title, year, length, genre, studioName, producer) StarsIn (movieTitle, starName) MovieStar (name, address, gender, birthdate) 我有三个表,电影(标题,年份,长度,类型,工作室名称,制片人),StarsIn(电影标题,starName),电影明星(名称,地址,性别,生日)

So basically i need to write a trigger for assuring that at all times, any star appearing in StarsIn also appears in MovieStar. 因此,基本上我需要编写一个触发器来确保在任何时候,出现在StarsIn中的任何一颗星星也都出现在MovieStar中。 I need to make the trigger for both insert and update events. 我需要为插入和更新事件创建触发器。

UPDATE: Ok so i changed my statement a little but i still can't figure this out 更新:好的,所以我改变了一点,但是我仍然无法弄清楚

CREATE OR REPLACE TRIGGER movieTrigger
  AFTER UPDATE OR INSERT ON STARSIN
  FOR EACH ROW
  WHEN(new.STARNAME NOT IN(SELECT "NAME" FROM MOVIESTAR))
  BEGIN
INSERT INTO MOVIESTAR("NAME")
VALUES(new.STARNAME)
END;

Now I am getting the error 现在我得到了错误

Error report:
ORA-02251: subquery not allowed here
02251. 00000 -  "subquery not allowed here"
*Cause:    Subquery is not allowed here in the statement.
*Action:   Remove the subquery from the statement.

I just learned that oracle does not support a subquery in the when clause... So i am trying to figure this out with limited knowledge. 我刚刚了解到oracle在when子句中不支持子查询。因此,我试图用有限的知识弄清楚这一点。 But if anyone has a clever way of doing this i would really like to know :-). 但是,如果有人有一个聪明的办法,我真的很想知道:-)。

Thanks again 再次感谢

You created a statement-level trigger. 您创建了一个语句级触发器。 It will fire once for each insert or update statement. 每个插入或更新语句将触发一次。 But a single insert or update statement can insert/update many rows in one go. 但是,一条插入或更新语句可以一次插入/更新许多行。 Your code however needs a single row and assumes that only a single row is inserted or updated. 但是,您的代码只需要一行,并假定仅插入或更新了一行。

What you need are rowlevel triggers ("FOR EACH ROW") if you want to follow this path. 如果要遵循此路径,则需要行级触发器(“ FOR EACH ROW”)。

Your trigger should be fired before (in this case) the insert of any row (currently it fires once for multiple rows inserted once) 您的trigger应该在insert任何row before (在这种情况下)触发(当前,对于插入一次的多行,它会触发一次)

I would recommend reading http://docs.oracle.com/cd/A97630_01/appdev.920/a96590/adg13trg.htm 我建议阅读http://docs.oracle.com/cd/A97630_01/appdev.920/a96590/adg13trg.htm

Its always better to use a foreign key constraint for ensuring that the value that appears in table b is present in table a , in this case there should be a foreign key in your table StarsIn for column starName referencing name in MovieStar table 它总是更好地使用外键约束确保出现在表中的值b存在于表a ,在这种情况下,应该有一个foreign key在表StarsInstarName引用nameMovieStar

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM