Oracle批量操作,存在则更新,不存在则插入

单条数据案例:

        T有a、b两个字段 a是主键。现在有记录(100, 2)要保存到T中,T中如果已经存在则更新字段b,没有插入。

类似Mysql:on duplicate key update

MERGE INTO T T1
 
USING (SELECT '100' AS a, 2 AS b FROM dual) T2
 
ON ( T1.a = T2.a)
 
WHEN MATCHED THEN
 
  UPDATE SET T1.b = T2.b
 
WHEN NOT MATCHED THEN 
 
  INSERT (a, b) VALUES(T2.a, T2.b);

Sql案例:

MERGE INTO MDM_FG T1 USING ( SELECT '1111' AS FGID, '我是嘉哥哦' AS FGNAME FROM dual ) T2 ON ( T1.FGID = T2.FGID ) 
WHEN MATCHED THEN
	UPDATE 
		SET T1.FGNAME = T2.FGNAME
WHEN NOT MATCHED THEN
	INSERT ( FGID, FGNAME )
		VALUES
		( T2.FGID, T2.FGNAME );

 多条数据案例:

Mybatis中xml批量执行Oracle的Sql必须加上 BEGIN END;

BEGIN 
     MERGE INTO A T1 USING 
		(SELECT #{temp.a, jdbcType=VARCHAR} AS a, #{temp.b, jdbcType=VARCHAR} AS b FROM dual) T2
ON
	(T1.a = T2.a ) 
WHEN MATCHED THEN
	UPDATE SET  T1.b = T2.b
WHEN NOT MATCHED THEN
	INSERT (a, b) VALUES (T2.a, T2.b)
	; 
END;

你可能感兴趣的:(Oracle业务场景系列,oracle,sql)