merge into 实现向表中更新内容·

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了merge into 实现向表中更新内容·相关的知识,希望对你有一定的参考价值。

表触发器2.0

行触发器获取的值改为放在中间表中

触发器在向目标表中写数据时,目标表的记录可能不完全,需要向目标表添加不存在的数据。

用到merge into 语法。

merge into  要更新的表(目标表)

using  记录完整的表(源表)

on  两表记录对比条件

when matched then

update

when not matched then

insert

注意:执行过程是源表中记录一条一条去匹配目标表内容,所以源表中数据不能有符合对比条件的重复数据

 

另:    某语句要查询不重复内容,为了让distinct只作用于某个字段,可以与group by 连用,然后在select中用count函数

 select *, count(distinct 字段) from table group by 字段

 

行触发器:

create or replace trigger qmfawtechnics_row --行触发器,保存更改的masterbsoid
after insert or update or delete
on qmfawtechnics
for each row
declare
p_count number;
begin
if inserting then
select count(*) into p_count
from trigger_qmfawtechnics --中间表已存在
where masterbsoid = :new.masterbsoid;
if p_count = 0 then
insert into trigger_qmfawtechnics
values(:new.masterbsoid, 0); --若已有,则不添加
end if;
end if;

if deleting then
select count(*) into p_count
from trigger_qmfawtechnics
where masterbsoid = :old.masterbsoid;
if p_count = 0 then
insert into trigger_qmfawtechnics
values(:old.masterbsoid, 1);
end if;
end if;

if updating then
select count(*) into p_count
from trigger_qmfawtechnics
where masterbsoid = :old.masterbsoid;
if p_count = 0 then
insert into trigger_qmfawtechnics
values(:old.masterbsoid, 1);
end if;
select count(*) into p_count
from trigger_qmfawtechnics
where masterbsoid = :new.masterbsoid;
if p_count = 0 then
insert into trigger_qmfawtechnics
values(:new.masterbsoid, 0);
end if;
end if;
end;

 

表触发器:

create or replace trigger qmfawtechnics_table
after insert or update or delete
on qmfawtechnics --表触发器,执行更新操作

begin
--更新工艺最大版序,并放入qmfawtechnicsmaxversionvalue表中
merge into qmfawtechnicsmaxversionvalue t1
using (select distinct masterbsoid
from trigger_qmfawtechnics) t2
on (t1.masterbsoid=t2.masterbsoid)
when matched then
update
set maxversionvalue = getmaxversionvalue(‘qmfawtechnics‘,t2.masterbsoid)
where masterbsoid=t2.masterbsoid
when not matched then
insert
values(t2.masterbsoid,getmaxversionvalue(‘qmfawtechnics‘,t2.masterbsoid));

--更新零件对应的工艺,放入technicscache缓存表
--注意顺序,以下操作要使用更新后的qmfawtechnicsmaxversionvalue表
merge into technicscache t1
using (select distinct a.bsoid, c.carnumber
from technicspart a
join qmpartCarNum c on c.partbsoid=a.partbsoid
join qmfawtechnicsmaster d on d.technicspart=a.bsoid
join trigger_qmfawtechnics e on e.masterbsoid=d.bsoid) t2
on ( t1.carnumber=t2.carnumber and t1.technicspartbsoid = t2.bsoid)
when matched then
update
set technicsbsoid = getJustTechnicsBsoid(t1.technicspartbsoid,t1.carnumber)
where technicspartbsoid = t2.bsoid
when not matched then
insert
values(t2.bsoid,t2.carnumber,getJustTechnicsBsoid(t2.bsoid,t2.carnumber));

delete trigger_qmfawtechnics;
end;

以上是关于merge into 实现向表中更新内容·的主要内容,如果未能解决你的问题,请参考以下文章

SQL中merge into用法

SQL中merge into用法

SQL之merge into(转)

SQL Server中的Merge Into

如何使用mysql语句向表中插入数据

oracle中merge into的使用