Oracle Trigger Simple SQL

时间:2012-12-21 18:28:10

标签: sql oracle triggers

我正在尝试编写此触发器,但它无法正常工作。我有一张桌子GIVING(捐赠者,接收者,礼物名称)和一张桌子PERSONS(pname,age,haircolor)。对于触发器,我希望它在捐赠者和接收者具有相同的头发颜色时吐出一条消息。琐碎,我知道,但我只是开始学习触发器而且完全坚持为什么这不会起作用。感谢。

create or replace TRIGGER SameHairColor
BEFORE INSERT OR UPDATE OF GIFTNAME ON GIVING
DECLARE
  haircolordonor varchar(255);
  haircolorreceiver varchar(255);
BEGIN
select persons.haircolor into haircolordonor
from persons, giving
where (donor = persons.pname);
select persons.haircolor into haircolorreceiver
from persons, giving
where (receiver = persons.pname);

if (haircolordonor = haircolorreceiver) then

dbms_output.put_line('Wow, they have the same haircolor!  Who would have thought?');
end if;

end;

我得到的错误信息是执行过程中的错误“确切提取返回超过请求的行数”,指向DECLARE下面的行...?

2 个答案:

答案 0 :(得分:0)

您不是将查询限制在插入/更新行的捐赠者/接收者。他们应该是这样的:

select persons.haircolor
into haircolordonor
from persons
where persons.pname = :NEW.donor;

顺便说一句:您的触发器仅在INSERT OR UPDATE OF GIFTNAME触发,而它应在INSERT OR UPDATE OF donor, receiver触发,您需要使用FOR EACH ROW

您的触发器应如下所示:

CREATE OR REPLACE TRIGGER SameHairColor
BEFORE INSERT OR UPDATE OF donor, receiver ON GIVING
  FOR EACH ROW
DECLARE
  haircolordonor varchar(255);
  haircolorreceiver varchar(255);
BEGIN
  select persons.haircolor into haircolordonor
  from persons
  where (persons.pname = :NEW.donor);
  select persons.haircolor into haircolorreceiver
  from persons
  where (persons.pname = :NEW.receiver);

  IF (haircolordonor = haircolorreceiver) THEN
    dbms_output.put_line('Wow, they have the same haircolor!  Who would have thought?');
  END IF;
END;

答案 1 :(得分:0)

CREATE OR REPLACE TRIGGER SameHairColor
BEFORE INSERT OR UPDATE OF GIFTNAME ON GIVING
REFERENCING NEW ROW AS new
FOR EACH ROW
DECLARE
  haircolordonor varchar(255);
  haircolorreceiver varchar(255);
BEGIN
select persons.haircolor into haircolordonor
from persons, giving
where (:new.donor = persons.pname);
select persons.haircolor into haircolorreceiver
from persons, giving
where (:new.receiver = persons.pname);

if (haircolordonor = haircolorreceiver) then
    dbms_output.put_line('Wow, they have the same haircolor!  Who would have thought?');
end if;

end;

也许这可能会有所帮助?