简体   繁体   中英

Oracle Trigger Simple SQL

I am attempting to write this trigger but it is not working right. I have a table GIVING(donor, receiver, giftname) and a table PERSONS(pname, age, haircolor). for the trigger I want it to spit out a message whenever the donor and receiver have the same hair color. Trivial, I know, but I'm just starting to learn triggers and am totally stuck on why this won't work. Thanks.

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;

The error message I get is error during execution "exact fetch returns more than requested number of rows", pointing to the row below DECLARE...?

You are not restricting your queries to the donor/receiver of the inserted/updated row. They should look like this:

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

BTW: Your trigger only fires on INSERT OR UPDATE OF GIFTNAME , while it should fire on INSERT OR UPDATE OF donor, receiver and you need to use FOR EACH ROW .

Your trigger should look like this:

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;
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;

Perhaps this might help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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