当前位置:K88软件开发文章中心编程全书编程全书01 → 文章内容

Oracle中的Merge语句

减小字体 增大字体 作者:佚名  来源:翔宇亭IT乐园  发布时间:2019-1-3 1:52:03

:2012-07-17 15:58:12

在Oracle中,可以使用merge语句实现对表的更新或插入。语法格式如下:

merge into tableName using tableName on(join_condition) when matched then update set...
when not matched then insert(...) values(...)

这个语句的意思是把using表合并到into表,合并条件是on(condition),当条件满足时只能是更新into表中的对应的记录,当条件不满足时,则也只能是往into表里面添加对应的数据,而该数据中也只能使用using表中当前记录对应的数据。

示例如下:

假设有一个student表,那么以下语句就可以实现当a的id大于b的id的时候把所有student的年龄加2,否则就新增一条记录。

merge into student a using student b on(a.id>b.id) when matched then update set age=age+2 when not matched then insert(id,name,age,sex,no)
values(b.id+100,b.name,b.age,b.sex,b.no);


Oracle中的Merge语句