Oracle中merge命令的簡單使用

來源:互聯網
上載者:User

Oracle中merge命令的簡單使用

merge命令

通過這個merge你能夠在一個SQL語句中對一個表同時執行inserts和updates操作

使用meger語句,可以對指定的兩個表執行合併作業,其文法如下:
MEGER INTO table1_name
USING table2_name ON join_condition
WHEN MATCHEO THEN UPDATE SET...
WHEN NOT MATCHED THEN INSERT ...VALUES...
文法說明如下:
table1_name表示需要合并的目標表。
table2_name表示需要合并的源表。
join_condition表示合并條件。
when matcheo then update表示如果符合合并的條件,則執行更新操作。
when not matched then insert表示如果不符合條件,則執行插入操作。

update和insert
    如果只是希望將源表中合格資料合併到目標表中,可以只使用update子句,如果希望將源表中不符合合并條件的資料合併到目標表中,可以只使用insert子句。
    在update子句和insert子句中,都可以使用where子句指定更新過插入的條件。這時,對於合併作業來說,提供了兩層過濾條件,第一層是合并條件,由meger子句中的on子句指定,第二層是update或insert子句中指定的where條件。從而使得合併作業更加靈活和精細。
在這裡我們建立兩張表,一張為person表,另一張為newpersono表,兩張表的結構是相同的
SQL> create table person(
  2  pid number(4),
  3  page number(3)
  4  );
表已建立。
--插入三行資料
SQL> insert into person values(1,20);
已建立 1 行。
SQL> insert into person values(2,21);
已建立 1 行。
SQL> insert into person values(3,22);
已建立 1 行。
SQL> create table newperson(
  2  pid number(4),
  3  page number(3)
  4  );
表已建立。
--插入三行資料
SQL> insert into newperson values(1,100);
已建立 1 行。
SQL> insert into newperson values(4,100);
已建立 1 行。
SQL> insert into newperson values(5,100);
已建立 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語句為當person中的pid等於newperson中的pid時,把person中的對應的page置為newperson中的age,當不符合時,向person插入不合格資料。執行的結果如下:
SQL> select * from person;
      PID      PAGE
---------- ----------
        1        100
        2        21
        3        22
        5        100
        4        100
--newperson表中的資料不會改變:
SQL> select * from newperson;
      PID      PAGE
---------- ----------
        1        100
        4        100
        5        100

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.