前言
上一章我们介绍了Oracle的临时表的使用方法《Oracle的临时表的使用》,就像我前面说的,多表关联查询的时候会用到临时表插入数据,然后再用select查行查询,在往临时表里插入数据的时候,我们经常会用到判断如果临时表里有了这部分数据我们就要更新数据,如果临时表里没有这部分数据我们就要插入,这个时候就到用了Merge into语句了。
语法介绍
像上面这样的例子如果在SQL里面实现会非常简单
if exists(select 1 from T where T.a='1001' )
update T set T.b=2 Where T.a='1001'
else
insert into T(a,b) values('1001',2);
而在Oracle里面要用到Merge into来实现(Oracle 9i引入的功能),其语法如下:
MERGE INTO table_name alias1
USING (table|view|sub_query) alias2ON (join condition)
WHEN MATCHED THEN
UPDATE table_name
SET col1 = col_val1,
col2 = col_val2
WHEN NOT MATCHED THEN
INSERT (column_list) VALUES (column_values);
用法实例
我们还是直接用上一章创建的那个临时表
我们先查一下数据源tskuplu
可以看到我们的商品表里面有两条数据
然后我们再查一下上一章已经创建的临时表temp_cstable
里面什么也没有,我们现在开始写语句。
判断temp_cstable表里的incode与tskuplu表里的plucode,如果存在的话把tskuplu里面Plulong字符值更新temp_cstable里的yhtotal字段值,如果不存在的话把tskuplu里的数据插入到temp_cstable里,其中xstotal用做plulong的值默认的yhtotal的值为0。
然后我们执行第一遍看一下结果
可以看到temp_cstable表里面有了两条数据,并且XStotal取的是tskuplu里的plulong值为1
我们再修改一下语句,让刚才这个merge into的语句执行两次
可以看到上面第一次不存在的话先插入数据,如果第二次存在的话,就更新临时表temp_cstable里面Yhtotal的值了。
完整代码
declare vi_count integer; vs_sSql varchar2(4000):=''; begin vs_sSql:= 'select count(*) from user_tables where table_name = upper(' || chr(39) || 'temp_cstable' || chr(39) || ')'; execute immediate vs_sSql into vi_count; dbms_output.put_line(vi_count); --判断temp_cstable的临时表是否存在,如果存在清空里面数据,不存在即创建 if vi_count>0 then vs_sSql := 'delete from temp_cstable'; execute immediate vs_sSql; else vs_sSql := ' create global temporary table temp_cstable ( incode varchar2(20), barcode varchar2(20), xstotal number, yhtotal number) on commit Preserve rows'; execute immediate vs_sSql; end if; /*判断temp_cstable表里的incode与tskuplu表里的plucode 如果存在的话把tskuplu里面Plulong字符值更新temp_cstable里的yhtotal字段值 如果不存在的话把tskuplu里的数据插入到temp_cstable里,其中xstotal用做plulong的值 默认的yhtotal的值为0 */ vs_sSql:= ' merge into temp_cstable t1 using(select * from tskuplu) t2 on (t1.incode=t2.plucode) when not matched then insert (incode,barcode,xstotal,yhtotal) values(t2.plucode,t2.pluname,t2.plulong,0) when matched then update set t1.yhtotal=t2.plulong '; execute immediate vs_sSql; execute immediate vs_sSql; end;
-END-