您好,登錄后才能下訂單哦!
Oracle中如何使用merge into語(yǔ)句,針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
語(yǔ)法介紹
像上面這樣的例子如果在SQL里面實(shí)現(xiàn)會(huì)非常簡(jiǎn)單
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來(lái)實(shí)現(xiàn)(Oracle 9i引入的功能),其語(yǔ)法如下:
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);
用法實(shí)例
我們還是直接用上一章創(chuàng)建的那個(gè)臨時(shí)表
我們先查一下數(shù)據(jù)源tskuplu
可以看到我們的商品表里面有兩條數(shù)據(jù)
然后我們?cè)俨橐幌律弦徽乱呀?jīng)創(chuàng)建的臨時(shí)表temp_cstable
里面什么也沒(méi)有,我們現(xiàn)在開(kāi)始寫(xiě)語(yǔ)句。
判斷temp_cstable表里的incode與tskuplu表里的plucode,如果存在的話把tskuplu里面Plulong字符值更新temp_cstable里的yhtotal字段值,如果不存在的話把tskuplu里的數(shù)據(jù)插入到temp_cstable里,其中xstotal用做plulong的值默認(rèn)的yhtotal的值為0。
然后我們執(zhí)行第一遍看一下結(jié)果
可以看到temp_cstable表里面有了兩條數(shù)據(jù),并且XStotal取的是tskuplu里的plulong值為1
我們?cè)傩薷囊幌抡Z(yǔ)句,讓剛才這個(gè)merge into的語(yǔ)句執(zhí)行兩次
可以看到上面第一次不存在的話先插入數(shù)據(jù),如果第二次存在的話,就更新臨時(shí)表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的臨時(shí)表是否存在,如果存在清空里面數(shù)據(jù),不存在即創(chuàng)建
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里的數(shù)據(jù)插入到temp_cstable里,其中xstotal用做plulong的值
默認(rèn)的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;
關(guān)于Oracle中如何使用merge into語(yǔ)句問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。