oracle函数mergin into用法


所有的MIS系统都存在一个同样的需求,就是对于特定的数据,在一次批量操作过程中,如果数据已经存在,则对存在的数据按照现有情况进行

    更新,如果不存在,则需要加入数据库。这时,我们就可以考虑采用 Oracle 的 MERGE 函数,其具体用法如下:

    MERGE INTO [your table-name] [rename your table here]
        USING
            (
                [write your query here]
            )[rename your query-sql and using just like a table]
        ON
            ([conditional expression here] AND [...]...)
        WHEN
            MATCHED
        THEN
            [here you can execute some update sql or something else ]
        WHEN
            NOT MATCHED
        THEN
            [execute something else here ! ]

    下面是实例:
    假设一个student表 有这种需求。如果学生ID存在则更改姓名。
    如果学生ID不存在 则插入学生信息。

    sql@kokooa>select * from student;

          S_ID S_NAME                    S_AGE
    ---------- -------------------- ----------
             1 李一                         15
             2 李二                         15
             3 李三                         11
             4 李四                         12
             5 李五                         13
             6 李六                         14

    sql@kokooa>select * from test001;

            ID NAME            TEL ADDRESS
    ---------- -------- ---------- --------------------
             1 aaa             234
             2 bbb             234
             3 ccc             234
             4 ddd
             5 王五            111 333
             6 张三             22
             7 李四             20


    merge into student s
    using
    (
       select id,name,tel from test001)x
       on
         (s.s_id=x.id)
       when matched
       then update set s_name=x.name
       when not matched
       then insert
        (s_id,s_name,s_age)
       values
        (x.id,x.name,x.tel);
    commit;

    最终结果:
    sql@kokooa>select * from student;

          S_ID S_NAME                    S_AGE
    ---------- -------------------- ----------
             1 aaa                          15
             2 bbb                          15
             3 ccc                          11
             4 ddd                          12
             5 王五                          13
             6 张三                         14
             7 李四                         20

    注意到 MERGE 语句在最后的“;”(分号),这仅仅代表 MERGE 为一条完整的 SQL 语句。同时,要说明一下 USING 语句下方的 SQL 语句。这个语句仅仅是为了给后面语句的执行做准备性的工作,因此,如果你需要的数据仅仅是通过参数传入的那些值的话你就不需要再利用传入进来的参数在重新从库中查询。在 Oracle 的系统表中,有张 Dual 表,这样,你便可以使用 “select [your arguments] from dual ”的方式来构建这里的 SQL 语句,其中 [your arguments] 是你得到的一系列的参数,由于Dual表是系统表,因此可以大幅提升SQL的执行效率。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3