zoukankan      html  css  js  c++  java
  • Merge into 用法

    Merge的用法
    Merge可以完成以下功能:
    1、    两个表之间数据的更新
    2、    进行进销存更新库存
    3、    进行表之间数据的复制
    语法说明:
    1、    在语句结束后一定要用分号,否则会提示错误。
    2、    Merge后为目标表,Using后为数据源表
    3、    如果有两个When matched,则必须使用and来限定第一个子句,一个子句必须制定一个update,另一个必须制定delete
    4、    When not matched by target,这个子句处理存在于数据源之中,但不存在目标之中的数据行。
    5、    When not matched等价于When not matched by target
    6、    When not mathed by source,这个子句处理,存在于目标中,但是不存在数据表之中的数据行
    一、两个表之间数据的更新
    create table test1 (col1 int,col2 varchar(100))
    create table test2 (col3 int,col4 varchar(100))
      
    insert into test1
    values(1,'wang'),(2,'trieagle')
    insert into test2(col3)
    values(1),(2)
    merge test2
    using test1
    on test1.col1=test2.col3
    when matched then update set col4=col2;
      
    select * from test2
    结果:
    col3        col4
    1           wang
    2           trieagle
    二、进行进销存更新库存
    Trade表为模拟进出库记录,正数表示入库,负数表示出库
    create table stock(id int,qty int)
    create table trade(id int ,qty int)
    go
    insert into stock
    values (1,10), (2,20)
    insert into trade
    values(1,10),(1,-5),(1,20),(2,10),(2,-30),(3,5)
      
    merge stock
    using (select id,qty=sum(qty) from trade group by id) K
    on stock.id=k.id
    when matched and (stock.qty+k.qty)=0 then delete
    when matched then update set stock.qty=stock.qty+k.qty
    when not matched by target then insert values(k.id,k.qty);
      
    select * from stock
    结果:
    id          qty
    1           35
    3           5
    三、进行表之间数据的复制
    drop table test1
    drop table test2
    create table test1 (col1 int,col2 varchar(100))
    create table test2 (col3 int,col4 varchar(100))
      
    insert into test1
    values(1,'wang'),(2,'trieagle')
      
    merge test2
    using test1 on test1.col1 =test2.col3
    when matched and col2!=col4 then update set col4=col2
    when not matched then insert values(col1,col2)
    when not matched by source then delete;
      
    select* from test2
    结果:
    col3        col4
    1           wang
    2           trieagle
      
    继续:删掉test1中的一行,然后增加一行
    Delete test1 where col1=1
    Insert into test1 values(3,'wyq')
    然后再执行
    merge test2
    using test1 on test1.col1 =test2.col3
    when matched and col2!=col4 then update set col4=col2
    when not matched then insert values(col1,col2)
    when not matched by source then delete;
      
    结果:
    col3        col4
    2           trieagle
    3           wyq
     
     
    转自:http://blog.csdn.net/gongjian0628/article/details/12751761
  • 相关阅读:
    2020-06-20 助教一周小结(第十七周)
    2020-06-14 助教一周小结(第十六周)
    2020-06-7助教一周小结(第14周)
    2020本科校招-从小白到拿到30k offer的学习经历
    2020-05-24助教一周小结(第13周)
    2020-05-17 助教一周小结(第十二周)
    2020-05-10 助教一周小结(第十一周)
    2020-05-04 助教一周小结(第十周)
    2020-04-26 助教一周小结(第九周)
    Ngnix搭建静态网页和安装wordpress
  • 原文地址:https://www.cnblogs.com/getpower/p/10815270.html
Copyright © 2011-2022 走看看