官方例子
我们先看看一个简单的例子,来介绍一个merge into的用法
merge into products p using newproducts np on (p.product_id = np.product_id)
when matched then
update set p.product_name = np.product_name
when not matched then
insert values(np.product_id, np.product_name, np.category)
在这个例子里。前面的merger into products using newproducts 表示的用newproducts表来merge到products表,merge的匹配关系就是on后面的条件子句的内容,这里根据两个表的product_id来进行匹配,那么匹配上了我们的操作是就是when matched then的子句里的动作了,这里的动作是update set p.product_name = np.product_name, 很显然就是把newproduct里的内容,赋值到product的product_name里。如果没有匹配上则insert这样的一条语句进去。
注意事项
- UPDATE或INSERT子句是可选的
- UPDATE和INSERT子句可以加WHERE子句
- 在ON条件中使用常量过滤谓词来insert所有的行到目标表中,不需要连接源表和目标表
- UPDATE子句后面可以跟DELETE子句来去除一些不需要的行
生产需求
客户有自己的orgcode,每个客户下属s2要从小到大排序,由于客户下属不知道什么时候更新,而且每个客户的下属数量不同,人工操作太麻烦,所以希望实现自动化分配s2的代码,例如orgcode为1000的客户,可能有3个下属,三个下属的s2分别为1000-1,1000-2,1000-3,如果新增一个则自动分配为1000-4
实现方案
设置定时脚本,每天自动更新
基层表设置bk5,bk6,bk7,分别保存最终分配的号码,当前最大的号码和旧/新码标识
代码如下:
#!/bin/bash
export ORACLE_HOME=$ORACLE_BASE/product/10.2.0/db_1
export ORACLE_SID=FRONTDB
export PATH=$ORACLE_HOME/bin:$ORACLE_HOME/OPatch:$PATH
$ORACLE_HOME/bin/sqlplus -S xxx/xxx <<EOF
merge into gjb_zgsxx a
using (select distinct orgcode,
max(to_number(bk6)) over(partition by ORGCODE ) max_con
from GJB_ZGSXX
where s2 is not null
) b
on (a.orgcode=b.orgcode and a.s2 is null)
when matched then
update set a.bk6=b.max_con where a.s2 is null;
merge into GJB_ZGSXX a
using (select b.orgcode, a.s1, a.max_con + b.rn con
from (select distinct orgcode,
s1,
max(decode(bk6,null,0,to_number(bk6))) over(partition by ORGCODE order by S1 asc) max_con
from GJB_ZGSXX) a,
(select orgcode,
s1,
bk6,
rank() over(partition by ORGCODE order by S1 asc) rn
from GJB_ZGSXX m
where m.bk7 is null) b
where a.s1 = b.s1
and a.orgcode = b.orgcode) b
on (a.ORGCODE = b.ORGCODE and a.S1 = b.S1)
when matched then
update set a.BK5 = b.con,
a.BK6 = b.con,
a.BK7 = 1;
merge into GJB_ZGSXX a
using (
select distinct ORGCODE,max(to_number(BK6)) over(partition by ORGCODE) max_num f
rom GJB_ZGSXX ) b
on (a.ORGCODE=b.ORGCODE)
when matched then
update set A.BK6=b.max_num,
a.BK7=1,
S2=ORGCODE||'-'||BK5 where s2 is null;
commit;
EOF