merge into 根据查询数据对已存在的表中数据执行删除、修改、新增操作,在实际应用中非常实用,可以减少insert、update、delete的书写。
基本语法:
merge into table_name tn using (select column_name,... from table_name ) tmp on tn.条件=tmp.条件
when matched then update/delete
when not matched then insert (tn.column_name,....) values (tmp.column_name,....)
当有些特殊条件的时候,比如更新表中存在的数据且tn.column_name>tmp.column_name的数据时,应该怎么做呢?
Oracle:
merge into table_name tn using (select column_name,... from table_name ) tmp on tn.条件=tmp.条件
when matched then update/delete where tn.column_name>tmp.column_name
when not matched then insert (tn.column_name,....) values (tmp.column_name,....)
DB2:
merge into table_name tn using (select column_name,... from table_name ) tmp on tn.条件=tmp.条件when matched tn.column_name>tmp.column_name and then update/deletewhen not matched then insert (tn.column_name,....) values (tmp.column_name,....)