zoukankan      html  css  js  c++  java
  • Oracle Meger into 函数

    Oracle 在 9i 引入了 merge 命令, 通过这个 merge 能够在一个SQL 语句中对一个表同时执行 inserts 和 updates 操作。Merge into 可以实现用 B 表来更新 A 表数据(如果匹配上),如果 A 表中没有,则把 B 表的数据插入 A 表中。

    管中窥豹

    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 MATHED THEN [here you can execute some update sql or something else ] 
    WHEN NOT MATHED THEN [execute something else here ! ] 
    

    举个栗子:

    merge into new_products p using old_products op 
    on (p.product_id = np.product_id) 
    when matched then 
    update set p.product_name = op.product_name 
    when not matched then 
    insert values(
    op.product_id, op.product_name, op.category) 
    
    

    使用 old_products 表中的输入插入 new_products 中,匹配关系为 on 后面的条件字句的内容。when matched then 就是根据匹配关系匹配上了,when not matched then 就是没有匹配上需要做的相应操作。网上的一般资料都显示在做 merge 的时候,这样同样的情况下,merge 的性能是优于同等功能的update/insert 语句的。

    在Oracle 10g中MERGE有如下一些改进:
    1、UPDATE 或 INSERT 子句是可选的
    2、UPDATE 和 INSERT 子句可以加 WHERE 子句
    3、UPDATE 子句后面可以跟 DELETE 子句来去除一些不需要的行

    UPDATE 或 INSERT 子句是可选的

    merge into new_products p using old_products op 
    on (p.product_id = np.product_id) 
    when matched then 
    update set p.product_name = op.product_name
    
    

    when matched then 和 when not matched then 都是可选则参数,可以根据具体的业务类型来进行数据库操作,而不用拘泥于原有特定的语法。

    添加 WHERE 子句

    merge into new_products p using old_products op 
    on (p.product_id = np.product_id) 
    when matched then 
    update set p.product_name = op.product_name where op.name like '%co2fe%'
    when not matched then 
    insert values(
    op.product_id, op.product_name, op.category) where op.name like '%co2fe%'
    
    

    在添加了 where 条件之后我们的 update/insert 就会变得更加的灵活,能够满足更多的业务需求。

    DELETE 子句来去除一些不需要的行

    merge into new_products p using old_products op 
    on (p.product_id = np.product_id) 
    when matched then 
    update set p.product_name = op.product_name 
    delete where op.name like '%co2fe%'
    when not matched then 
    insert values(
    op.product_id, op.product_name, op.category)
    
    

    同样的,使用 delete 语句之后我们可以实现更多的功能和业务,扩展了 merge into 的使用面。

    本文由个人 hexo 博客 co2fe.com 迁移
    date: 2017-09-12 15:38:41

  • 相关阅读:
    MongoDB 2.4、备份
    MongoDB 2.3复制(副本集)
    MongoDB 2.2安全
    isMobile 一个简单的JS库,用来检测移动设备
    修改ECSHOP,支持图片云存储化(分离到专用图片服务器)
    压缩代码加速ecshop程序页面加载速度
    ecshop改造读写分离
    ecshop在nginx下实现负载均衡
    运用@media实现网页自适应中的几个关键分辨率
    在ECSHOP首页今日特价(促销商品)增加倒计时效果
  • 原文地址:https://www.cnblogs.com/manastudent/p/10190877.html
Copyright © 2011-2022 走看看