话不多说直接记录!(^_−)☆
自动判断是新增还是修改的关键字:
MERGE INTO
MERGE 语法:
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 ! ]
例如我们想插入一条数据 {ID=2,NAME=‘newtest2’} 那么可以这么写:
MERGE INTO TEST T1
USING (SELECT '2' as ID, 'newtest2' as NAME FROM dual) T2 on (T1.ID=T2.ID)
WHEN MATCHED THEN UPDATE SET T1.NAME=T2.NAME
WHEN NOT MATCHED THEN INSERT (T1.ID, T1.NAME) VALUES (T2.ID, T2.NAME );
注意:
Merge Into的原理是,从using 搜出来的结果逐条与on条件匹配,然后决定是update还是Insert。 当USING后面的sql没有查询到数据的时候,Merge Into语句是不会执行update和Insert操作的。
所以要想让Merge Into正常运行,要保证USING 后面的SELECT有数据,个人喜欢使用DUAL表作为USING后的表,方便自己控制
本次记录到此结束,欢迎订阅、关注、收藏、评论、点赞哦~~( ̄▽ ̄~)~
哇咔咔(∪。∪)。。。zzz