sql实现多行数据比对更新或插入操作

Merge语法
MERGE [hint] INTO [schema ] table [t_alias]
USING [schema ]{ table | view | subquery } [t_alias]
ON ( condition )
WHEN MATCHED THEN merge_update_clause
WHEN NOT MATCHED THEN merge_insert_clause;

1)创建一个“比例因子”表

-- Create table
create table LF_FACT_GL
(
  ID        NUMBER(10),
  VALID     NUMBER(1) default 1 not null,
  ZONE_ID   NUMBER(10),
  FACTOR_PG NUMBER(12,6) default 0 not null,
  FACTOR_QG NUMBER(12,6) default 0 not null,
  FACTOR_PL NUMBER(12,6) default 0 not null,
  FACTOR_QL NUMBER(12,6) default 0 not null,
  CASE_ID   NUMBER(10) not null,
  V_LEVEL   NUMBER(10) default 0
)
tablespace USERS
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 64K
    minextents 1
    maxextents unlimited
  );
 comment on column LF_FACT_GL.CASE_ID
  is '作业编号';
 comment on column LF_FACT_GL.V_LEVEL
  is '电压等级,固定;';
 comment on column LF_FACT_GL.ZONE_ID
  is '分区编号';


2)需求描述
   用户可以将某个作业的比例因子导入到另一个作业下。如果另一个作业的比例因子中的“电压等级”和“分区编号” 与操作的作业下的比例因子的电压等级”和“分区编号”分别相等,则做更新操作,否则做插入操作。

3)实现的sql(mybatis)
 

<insert id="insertOrUpdate" parameterType="map">
		 MERGE INTO LF_FACT_GL T1  
         USING (SELECT ID ,VALID ,ZONE_ID , FACTOR_PG,FACTOR_QG ,FACTOR_PL,FACTOR_QL ,CASE_ID ,V_LEVEL
                FROM LF_FACT_GL WHERE ID IN
                <foreach collection="iDs" index="index" item="item" open="(" separator="," close=")">  
                 #{item}  
                </foreach> 
               ) T2 
         ON (T1.ZONE_ID = T2.ZONE_ID AND T1.V_LEVEL = T2.V_LEVEL AND T1.CASE_ID = #{caseID} )   
         WHEN NOT MATCHED THEN  
         INSERT  VALUES 
              ( SEQ_PLSF_TBL.NEXTVAL , T2.VALID,T2.ZONE_ID,
                T2.FACTOR_PG,T2.FACTOR_QG,
                T2.FACTOR_PL,T2.FACTOR_QL,#{caseID},T2.V_LEVEL
               )   
         WHEN MATCHED THEN 
         UPDATE SET T1.VALID = T2.VALID,
                    T1.FACTOR_PG = T2.FACTOR_PG,T1.FACTOR_QG = T2.FACTOR_QG,
                    T1.FACTOR_PL = T2.FACTOR_PL,T1.FACTOR_QL = T2.FACTOR_QL
         
	</insert>
  

  map(iDs:String[比例因子编号],aseID:作业编号)


  merge 时,on(join 字段)不可以参加update ,否则报错(0n 关联字段不能更新 字段)

你可能感兴趣的:(SQL批量插入,sql 多行对比插入或修改,sql批量修改,sql MERGE USING)