表 zyj 结构如下:id、jh(井号)、xmlb(项目类别)、rq(日期)、zyzl(作业质量)
id是唯一的,jh+rq也能够唯一确定一条记录。要求:
每当Insert一条新记录,如果xmlb=“措施”,那么从表中查找该jh此次rq之前的最新的一条记录,如果存在,则将找到的记录的zyzl更新为“优质”。请问该如何写呢??
id是唯一的,jh+rq也能够唯一确定一条记录。要求:
每当Insert一条新记录,如果xmlb=“措施”,那么从表中查找该jh此次rq之前的最新的一条记录,如果存在,则将找到的记录的zyzl更新为“优质”。请问该如何写呢??
after insert
ON zyj
FOR EACH ROW
DECLARE v_cnt NUMBER;
PRAGMA AUTONOMOUS_TRANSACTION; --添加自治事务
BEGIN
if :new.xmlb='措施' then
--查找是否存在之前的记录
Select Count(*) Into v_cnt From zyj Where xmlb=:new.xmlb;
if v_cnt > 0 then
:new.xmlb='优质';
end if;
end if;
insert into zyj values(:new.id,:new.jh,:new.xmlb,:new.rq,:new.zyzl);
commit;
END;
没错,当在表zyj插入记录并且仅当新的xmlb="措施"时触发
找到同一井号(jh=new.jh)并且是 rq<new.rq 的最新一条记录, 更新zyzl为“优质”
rq是date型的,就年月日。可能存在多条记录,也可能只有一条记录,也可能一条记录都没有。当然如果一条都没有就不用做任何操作了。回2楼:
我要更新的是一条老记录,而不是new.zyzl,另外,after类型的触发器里好象不能用:new吧?
create or replace trigger trg_ins_zyj
before insert ON zyj
FOR EACH ROW v_rq zyj.rq%type;BEGIN
if :new.xmlb = '措施' then
--查找是否存在之前的记录
select max(rq)
into v_rq
From zyj
Where jh = :new.jh
and xmlb = :new.xmlb;
if v_rq is not null then
update zyj
set zyzl = '优质'
where jh = :new.jh
and xmlb = :new.xmlb
and rq = v_rq;
commit;
end if;
end if;
END;
before insert ON zyj
FOR EACH ROW
declare
v_rq zyj.rq%type;BEGIN
if :new.xmlb = '措施' then
--查找是否存在之前的记录
select max(rq)
into v_rq
From zyj
Where jh = :new.jh
and xmlb = :new.xmlb;
if v_rq is not null then
update zyj
set zyzl = '优质'
where jh = :new.jh
and xmlb = :new.xmlb
and rq = v_rq;
commit;
end if;
end if;
END;
after insert on zyj
for each row
declare
pragma autonomous_transaction;
begin
if(:new.xmlb = '措施') then
update zyj set zyzl='优质' where jh = :new.jh and rq = (select max(rq) from zyj where jh = :new.jh);
commit;
end if;
end insert_tri;
我自己写的和5楼的基本一样,但就是不成功,刚刚终于发现是我的另一个trigger出了问题郁闷啊把那个出错的trigger删了,一切正常了。。