如何在触发器里写:当一张表被更新时,更新它关联的一张表
有两张表,关联字段是HEAD_ID;A表Table1,有HEAD_ID,LINE_ID,QTY字段;一个HEAD_ID有多行;B表Table2,有HEAD_ID,SUMQ...
有两张表,关联字段是HEAD_ID;
A表Table1,有HEAD_ID,LINE_ID, QTY字段;一个HEAD_ID有多行;
B表Table2,有HEAD_ID, SUMQTY字段;一个HEAD_ID只有一行;
现在要写一个触发器,当Table1更新/新增或者删除行时,自动对QTY字段根据HEAD_ID进行汇总,并更新到Table2中对应的HEAD_ID的SUMQTY字段;
请教,多谢!
SQL SERVER语句 展开
A表Table1,有HEAD_ID,LINE_ID, QTY字段;一个HEAD_ID有多行;
B表Table2,有HEAD_ID, SUMQTY字段;一个HEAD_ID只有一行;
现在要写一个触发器,当Table1更新/新增或者删除行时,自动对QTY字段根据HEAD_ID进行汇总,并更新到Table2中对应的HEAD_ID的SUMQTY字段;
请教,多谢!
SQL SERVER语句 展开
展开全部
哎。。。刚开完会,不然早就弄好了,给你加了会儿班,呵呵。
环境—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;
有问题再追问,望采纳啊。
追问
不好意思,是SQL SERVER,忘了说了
追答
create trigger tr_zhidao
on system.zhidao_20131014_tab2_1
for insert,update,delete
as
declare @oldQTY number,@newQTY number,@oldHID varchar2(10),@newHID varchar2(10);
begin
if ((exists (select 1 from inserted)) and (exists (select 1 from deleted)))
begin
select @newQTY=QTY,@newHID=head_id from inserted;
select @oldQTY=QTY from deleted;
update system.zhidao_20131014_tab2_2 t set SUMQTY=SUMQTY - @oldQTY + @newQTY where t.head_id=@newHID;
end
else if (exists (select 1 from inserted) and not exists (select 1 from deleted))
begin
select @newQTY=QTY,@newHID=head_id from inserted;
update system.zhidao_20131014_tab2_2 t set SUMQTY=SUMQTY + @newQTY where t.head_id=@newHID;
end
else if (not exists (select 1 from inserted) and exists (select 1 from deleted))
begin
select @oldQTY=QTY,@oldHID=head_id from deleted;
update system.zhidao_20131014_tab2_2 t set SUMQTY=SUMQTY - @oldQTY where t.head_id=@oldHID;
end
end
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询