ORALCE 語法: MERGE INTO

參考: 
     https://www.cnblogs.com/relucent/p/4166544.html

當我們遇到不存在就保存,存在即更新的需求的時,MERGE INTO 是我們最好的選擇。
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 MATCHED THEN [here you can execute some update sql or something else ] 
WHEN NOT MATCHED THEN [execute something else here ! ] 

例子:

MERGE INTO USER T1
USING (SELECT userId FROM dual ) T2
ON ( T1.userId =T2.userId  AND T1.userType =T2.userType )
WHEN  MATCHED THEN
UPDATE
SET
T1.userName=?
WHERE T1.userId = T2.userId AND T1.userType =T2.userType		
WHEN  NOT MATCHED THEN
INSERT
(userId, userName)
VALUES
(?,?
)

Mybatis 中批量提交的例子:

<insert id="saveUser" parameterType="java.util.List">

			MERGE INTO userT1
			USING (SELECT #{item.userId} as  userId
			,#{item.userType} as  userType
			FROM dual ) T2
			ON ( T1.userId=T2.userId and T1.userType =T2.userType)
			WHEN  MATCHED THEN
			UPDATE
			SET
			T1.userName=#{item.userName,jdbcType=VARCHAR}
			WHERE T1.userId=T2.userId and T1.userType =T2.userType
			WHEN  NOT MATCHED THEN
			INSERT
			(userName)
			VALUES
			(#{item.userName}
			)		
		
	</insert>

 

USING搜索所有的符合條件的數據,用ON 中表達式進行比較, 如果存在執行更新操作,不存在就存入.

注: update 中的 where 的表達式 應該與ON  的表達式完全一樣。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章