在oracle中,merge命令可以在一個(gè)sql語(yǔ)句中對(duì)一個(gè)表同時(shí)執(zhí)行inserts和updates操作,使用merge語(yǔ)句,常用于對(duì)指定的兩個(gè)表執(zhí)行合并操作,語(yǔ)法為“MEGER INTO 合并目標(biāo)表 using 合并源表 ON 條件”。
本教程操作環(huán)境:Windows10系統(tǒng)、Oracle 11g版、Dell G3電腦。
oracle中merge的用法是什么
merge命令
通過(guò)這個(gè)merge你能夠在一個(gè)SQL語(yǔ)句中對(duì)一個(gè)表同時(shí)執(zhí)行inserts和updates操作
使用meger語(yǔ)句,可以對(duì)指定的兩個(gè)表執(zhí)行合并操作,其語(yǔ)法如下:
MEGER?INTO?table1_name USING?table2_name?ON?join_condition WHEN?MATCHEO?THEN?UPDATE?SET... WHEN?NOT?MATCHED?THEN?INSERT?...VALUES...
語(yǔ)法說(shuō)明如下:
table1_name表示需要合并的目標(biāo)表。
table2_name表示需要合并的源表。
join_condition表示合并條件。
when?matcheo?then?update表示如果符合合并的條件,則執(zhí)行更新操作。
when?not?matched?then?insert表示如果不符合條件,則執(zhí)行插入操作。
update和insert
如果只是希望將源表中符合條件的數(shù)據(jù)合并到目標(biāo)表中,可以只使用update子句,如果希望將源表中不符合合并條件的數(shù)據(jù)合并到目標(biāo)表中,可以只使用insert子句。
在update子句和insert子句中,都可以使用where子句指定更新過(guò)插入的條件。這時(shí),對(duì)于合并操作來(lái)說(shuō),提供了兩層過(guò)濾條件,第一層是合并條?件,由meger子句中的on子句指定,第二層是update或insert子句中指定的where條件。從而使得合并操作更加靈活和精細(xì)。
在這里我們創(chuàng)建兩張表,一張為person表,另一張為newpersono表,兩張表的結(jié)構(gòu)是相同的
SQL>?create?table?person( 2??pid?number(4), 3??page?number(3) 4??);
表已創(chuàng)建。
–插入三行數(shù)據(jù)
SQL>?insert?into?person?values(1,20);
已創(chuàng)建?1?行。
SQL>?insert?into?person?values(2,21);
已創(chuàng)建?1?行。
SQL>?insert?into?person?values(3,22);
已創(chuàng)建?1?行。
SQL>?create?table?newperson( 2??pid?number(4), 3??page?number(3) 4??);
表已創(chuàng)建。
--插入三行數(shù)據(jù) SQL>?insert?into?newperson?values(1,100);
已創(chuàng)建?1?行。
SQL>?insert?into?newperson?values(4,100);
已創(chuàng)建?1?行。
SQL>?insert?into?newperson?values(5,100);
已創(chuàng)建?1?行。
SQL>?select?*?from?person; PID???????PAGE ----------?---------- 1?????????20 2?????????21 3?????????22 SQL>?select?*?from?newperson; PID???????PAGE ----------?---------- 1????????100 4????????100 5????????100 SQL>?merge?into?person?p1 2??using?newperson?p2 3??on?(p1.pid=p2.pid) 4??when?matched?then 5????update?set?p1.page=p2.page 6??when?not?matched?then 7????insert?(pid,page)?values(p2.pid,p2.page);
3?行已合并。
–上面的sql語(yǔ)句為當(dāng)person中的pid等于newperson中的pid時(shí),把person中的對(duì)應(yīng)的page置為newperson中的age,當(dāng)不符合時(shí),向person插入不符合條件的數(shù)據(jù)。執(zhí)行的結(jié)果如下:
SQL>?select?*?from?person; PID???????PAGE ----------?---------- 1????????100 2?????????21 3?????????22 5????????100 4????????100 --newperson表中的數(shù)據(jù)不會(huì)改變: SQL>?select?*?from?newperson; PID???????PAGE ----------?---------- 1????????100 4????????100 5????????100
推薦教程:《Oracle視頻教程》