哎。。。刚开完会,不然早就弄好了,给你加了会儿班,呵呵。
环境—oracle
最不理想的就是行级触发器里面不用使用select原表等操作,而表级触发器又不能用:new和:old,
所以只能这样判断update、insert、delete来实现,否则得使用行级和表级和中间表才能实现,比较麻烦了。
--建表:
create table system.zhidao_20131014_tab2_1
(
HEAD_ID varchar2(10),
LINE_ID varchar2(10),
QTY number
);
create table system.zhidao_20131014_tab2_2
(
HEAD_ID varchar2(10),
SUMQTY number
);
--造数:
insert into system.zhidao_20131014_tab2_1
select 'H1','1',100 from dual
union all
select 'H1','2',200 from dual
union all
select 'H1','2',300 from dual
union all
select 'H1','2',100 from dual;
insert into system.zhidao_20131014_tab2_2
select 'H1',700 from dual;
commit;
--触发器:
create or replace trigger tr_zhidao
after insert or update or delete
on system.zhidao_20131014_tab2_1
for each row
begin
case
when updating then
update system.zhidao_20131014_tab2_2 t set SUMQTY=SUMQTY - :old.QTY + :new.QTY where t.head_id=:new.head_id;
when inserting then
update system.zhidao_20131014_tab2_2 t set SUMQTY=SUMQTY + :new.QTY where t.head_id=:new.head_id;
when deleting then
update system.zhidao_20131014_tab2_2 t set SUMQTY=SUMQTY - :old.QTY where t.head_id=:old.head_id;
end case;
end;
--测试:
--insert
insert into system.zhidao_20131014_tab2_1
select 'H1','3',300 from dual;
--delete
delete system.zhidao_20131014_tab2_1 where HEAD_ID='H1' and LINE_ID='3';
--update
update system.zhidao_20131014_tab2_1 set QTY=1000 where QTY=300;
有问题再追问,望采纳啊。