merge into是一个dml语句,也需要通过rollback和commit 结束事务。
UPDATE或INSERT子句可以二选一。
10g之前必须insert into和update都要存在,不是update就是insert,只能二选一。而10g里就是可选了。
比如下面的例子,可以只存在update或者insert
merge into oldproducts op using newproducts np on (op .product_id = np.product_id)
when matched then
update set op.product_name = np.product_name
以上例子说明有匹配的时候就更新,不匹配的情况下就不处理了。
2. UPDATE和INSERT子句可以加上WHERE子句
这也是一个功能性的改进,这个where的作用是一个过滤的条件,加入一些额外的条件,对只对满足where条件的进行update和insert
merge into oldproducts op using (select * from newproducts) np on (op.product_id = np.product_id)
when matched then
update set op.product_name = np.product_name where np.product_name like 'LV%'
insert里也可以加入where,比如
merge into oldproducts op using (select * from newproducts) np on (op.product_id = np.product_id)
when matched then
update set op.product_name = np.product_name where np.product_name like 'LV%'
when not matched then
insert values(np.product_id, np.product_name, np.category) where np.product_name like 'LV%'
3. 在ON条件中使用常量过滤条件来insert所有的行到目标表中,不需要连接源表和目标表
merge into oldproducts op using (select * from newproducts) np on (1=0)
when matched then
update set op.product_name = np.product_name
when not matched then
insert values(np.product_id, np.product_name, np.category)
4. UPDATE子句后面可以通过DELETE子句来去除一些不需要的行,delete只能和update配合,从而达到删除满足where条件的子句的纪录
merge into oldproducts op using (select * from newproducts) np on (p.product_id = np.product_id)
when matched then
update set op.product_name = np.product_name delete where op.product_id = np.product_id where np.product_name like 'LV%'
when not matched then
insert values(np.product_id, np.product_name, np.category)
閱讀更多 老孔說編程 的文章