我有一张像这样的表:
create table person(
id_person number(5),
city varchar(20)
);
insert into person values (1, 'NY');
insert into person values (2, 'Los Angeles');
我想将“人”动作注册到新表中:
create table move_city(
new_location varchar(200)
);
我有触发器来执行此操作:
create or replace trigger person_movement
after update of city on person
for each row
begin
insert into move_city values('The person has moved from ' ||:old.city|| ' to ' || :new.city);
end;
/
正在按预期工作。
如果我这样做:
update person set city='Boston' where id_person=1;
我在move_city: “这个人已从纽约搬到波士顿了”
我的问题是,我想把'id_person'放在'move_city'中并获得类似'有id的人......从纽约搬到波士顿',我不知道我有什么需要在我的触发器中做。
我的意思是触发器上有这样的东西。
insert into move_city values('The person with ' ||id_person|| ' has moved from ' ||:old.city|| ' to ' || :new.city);
但它不起作用。
有什么建议吗?
更新
我尝试过:
create or replace trigger person_movement
after update of city on person
for each row
declare
id2 person.id_person%type;
begin
select id_person into id2 from person where id_person=:new.id_person;
insert into move_city values('The person with ' ||id2|| ' has moved from ' ||:old.city|| ' to ' || :new.city);
end;
/
但是当我这样做时:
update person set city='Boston' where id_person=1;
我获得:
ORA-04091:表SYSTEM.PERSON正在变异,触发器/函数可能看不到它
ORA-06512:在“SYSTEM.PERSON_MOVEMENT”第4行
ORA-04088:执行触发器'SYSTEM.PERSON_MOVEMENT'
时出错答案 0 :(得分:1)
您可以在此处使用:new
或:old
:
INSERT INTO move_city
( new_location )
VALUES
( 'The person with ' || :new.id_person|| ' has moved from ' ||:old.city|| ' to ' || :new.city);
但是,我认为对于您的move_city
表,最好的办法是为id_person
,old_location
和new_location
添加单独的列,然后添加支持从表中检索数据时的信息。这样你就可以这样做:
INSERT INTO move_city
( id_person, old_location, new_location )
VALUES
( :new.id_person, :old.city, :new.city );
(在DATE
中设置move_city
列,默认值为SYSDATE
也是个好主意。)
在您的触发器中,您只能执行old.city
与new.city
不同的插入内容:
IF ( old.city != new.city OR old.city IS NULL ) THEN
INSERT INTO move_city
( id_person, old_location, new_location )
VALUES
( :new.id_person, :old.city, :new.city );
END IF;
希望这有帮助。