1,insert 和update是可选的 2,UPDATE 和INSERT 后面可以跟WHERE 子句 3,在ON条件中可以使用常量来insert 所有的行到目标表中,不需要连接到源表和目标表 4,UPDATE 子句后面可以跟delete 来去除一些不需要的行。
举例:
- createtable PRODUCTS
- (
- PRODUCT_ID INTEGER,
- PRODUCT_NAME VARCHAR2(60),
- CATEGORY VARCHAR2(60)
- );
- insertinto PRODUCTS values (1501, 'VIVITAR 35MM', 'ELECTRNCS');
- insertinto PRODUCTS values (1502, 'OLYMPUS IS50', 'ELECTRNCS');
- insertinto PRODUCTS values (1600, 'PLAY GYM', 'TOYS');
- insertinto PRODUCTS values (1601, 'LAMAZE', 'TOYS');
- insertinto PRODUCTS values (1666, 'HARRY POTTER', 'DVD');
- commit;
- createtable NEWPRODUCTS
- (
- PRODUCT_ID INTEGER,
- PRODUCT_NAME VARCHAR2(60),
- CATEGORY VARCHAR2(60)
- );
- insertinto NEWPRODUCTS values (1502, 'OLYMPUS CAMERA', 'ELECTRNCS');
- insertinto NEWPRODUCTS values (1601, 'LAMAZE', 'TOYS');
- insertinto NEWPRODUCTS values (1666, 'HARRY POTTER', 'TOYS');
- insertinto NEWPRODUCTS values (1700, 'WAIT INTERFACE', 'BOOKS');
- commit;
- 1,可省略的update 或者insert
- MERGE INTO products p
- 2 USING newproducts np
- 3 ON (p.product_id = np.product_id)
- 4 WHEN MATCHED THEN
- 5 UPDATE
- 6 SET p.product_name = np.product_name,
- 7 p.category = np.category;
使用表newproducts中的product_name 和category字段来更新表products 中相同product_id的product_name 和category.
2,当条件不满足的时候把newproducts表中的数据INSERT 到表products中。
- MERGE INTO products p
- USING newproducts np
- ON (p.product_id = np.product_id)
- WHENNOT MATCHED THEN
- INSERT
- VALUES (np.product_id, np.product_name,
- np.category);
3,带条件的insert 和update
- MERGE INTO products p
- USING newproducts np
- ON (p.product_id = np.product_id)
- WHEN MATCHED THEN
- UPDATE
- SET p.product_name = np.product_name
- WHERE p.category = np.category;
insert 和update 都带有where 字句
- MERGE INTO products p
- USING newproducts np
- ON (p.product_id = np.product_id)
- WHEN MATCHED THEN
- UPDATE
- SET p.product_name = np.product_name,
- p.category = np.category
- WHERE p.category = 'DVD'
- WHENNOT MATCHED THEN
- INSERT
- VALUES (np.product_id, np.product_name, np.category)
- WHERE np.category != 'BOOKS'
4,无条件的insert
- MERGE INTO products p
- USING newproducts np
- ON (1=0)
- WHENNOT MATCHED THEN
- INSERT
- VALUES (np.product_id, np.product_name, np.category)
- WHERE np.category = 'BOOKS'
5,delete 子句
1 merge into products p 2 using newproducts np 3 on(p.product_id = np.product_id) 4 when matched then 5 update 6 set p.product_name = np.product_name 7 delete where category = 'macle1_cate';
select *
from products;
PRODUCT_ID PRODUCT_NAME CATEGORY --------------------------------------- -------------------- -------------------- 1502 macle22 macle2_cate 1503 macle3 macle2_cate 1504 macle macle1_cate 1505 macle5 macle5_cate
1504 中的macle1_cate 满足delete where,但是不满足 on 中的条件,所以没有被删除。!!!!!!重点