Oracle应用之merge合并更新函数

2022-05-07 16:48:36 浏览数 (1)

本博客介绍一下Oracle merge合并函数,业务场景:新增数据的时候要先查询数据库是否已经有改数据,有数据就更新数据,没数据才新增数据,这是很常见的业务场景,如果是用Oracle数据库的话,其实直接用merge函数效率更快,而且merge函数性能也相对比较好

merge函数的语法:

代码语言:javascript复制
MERGE INTO table_name alias1 
USING (table|view|sub_query) alias2
ON (join condition) 
WHEN MATCHED THEN 
    UPDATE table_name 
    SET col1 = col_val1, 
           col2 = col_val2 
WHEN NOT MATCHED THEN 
    INSERT (column_list) VALUES (column_values); 

举个例子: SQL实现,意思是有数据就更新,没数据才新增

代码语言:javascript复制
MERGE INTO t_config_related A1 USING(select '97547758-6f85-419e-85f9-b8f711ca2660' seq,
          '97547758-6f85-419e-85f9-b8f711ca2658' tipsSeq,
          to_number('1') appLevel,
          '24e1ccc38d9542189d1cc6c23f814a18' relaSeq from dual) A2
ON(A1.seq = A2.seq)
WHEN MATCHED THEN
UPDATE SET
        A1.tips_seq = A2.tipsSeq,            
        A1.app_level = A2.appLevel,
        A1.rela_seq = A2.relaSeq
WHEN NOT MATCHED THEN
INSERT(seq , tips_seq , app_level , rela_seq)
VALUES(A2.seq , A2.tipsSeq , A2.appLevel , A2.relaSeq);
代码语言:javascript复制
/**
   	 * 批量更新保存地区关联信息
   	 * @date   2019年2月21日上午11:17:10
   	 * @return
   	 */
 
   	@RequestMapping("/batchSaveTipsAreaConfig")
   	@ResponseBody
   	public ResultModel batchSaveTipsConfig(ApprTipsRelatedModel relatedModel) {
 
   		List<ApprTipsRelatedModel> areaTipsList = new ArrayList<ApprTipsRelatedModel>();
 
   		//封装批量更新的地区列表
 
   		String[] areaSeqs = StringUtils.split(relatedModel.getAreaSeq(),",");
 
   		for (String areaSeq : areaSeqs) {
 
   			ApprTipsRelatedModel areaRelatedModelNew = new ApprTipsRelatedModel();
 
   			areaRelatedModelNew.setSeq(commonService.generateUUID());
 
   			areaRelatedModelNew.setTipsSeq(relatedModel.getTipsSeq());
 
   			areaRelatedModelNew.setAppLevel(NumConstant.COMMON_NUM_TREE);
 
   			areaRelatedModelNew.setRelaSeq(areaSeq);
 
   		    areaTipsList.add(areaRelatedModelNew);
 
   	}
 
   		//批量更新新增数据
 
   		try {
 
   			this.tipsConfigService.batchSaveTipsRelatedConfig(areaTipsList);
 
   			return ResultModel.success("保存成功");
 
   		} catch(Exception e) {
 
   			logger.error("批量绑定地区异常:{}" e);
 
  			throw new SuperControllerException();
 
   		}
 
   	}

注意要点: 在开发中我遇到一个异常,mybatis打印出来的SQL是这样的:

代码语言:javascript复制
Preparing: MERGE INTO appr_tips_config_related A1 ? USING( ? ? ? ? ? select ? seq , ? tipsSeq , ? appLevel , ? relaSeq from dual ? ? ? ? ) A2 ? ON( ? ? ? ? ?A1.seq = A2.seq ? ? ?) ? WHEN MATCHED THEN ? ? UPDATE SET A1.seq = A2.seq, A1.tips_seq = A2.tipsSeq, A1.app_level = A2.appLevel, A1.rela_seq = A2.relaSeq ? ? ?WHEN NOT MATCHED THEN ? ? ?INSERT(seq,tip_seq,app_level,rela_seq) ? ? ? ? VALUES(A2.seq , A2.tipsSeq , A2.appLevel , A2.relaSeq) 

可以看出什么问题?打印出的SQL有很多问号,那是因为SQL有空格导致的,所以使用merge函数不用随便加空格,不然会报错的

代码语言:javascript复制
? USING( ? ? ? ? ? select ? seq , ? tipsSeq , ? appLevel , ? relaSeq from dual ? ? ? ? ) A2 ? ON( ? ? ? ? ?A1.seq = A2.seq ? ? ?) ? 

0 人点赞