阅读更多
该命令使用一条语句从一个或者多个数据源中完成对表的更新和插入数据. ORACLE 9i 中,使用此命令必须同时指定UPDATE 和INSERT 关键词,ORACLE 10g 做了如下改动。
1,insert 和update是可选的 2,UPDATE 和INSERT 后面可以跟WHERE 子句 3,在ON条件中可以使用常量来insert 所有的行到目标表中,不需要连接到源表和目标表 4,UPDATE 子句后面可以跟delete 来去除一些不需要的行。
举例:
1.create table PRODUCTS
2. (
3. PRODUCT_ID INTEGER,
4. PRODUCT_NAME VARCHAR2(60),
5. CATEGORY VARCHAR2(60)
6. );
7.
8. insert into PRODUCTS values (1501, 'VIVITAR 35MM', 'ELECTRNCS');
9. insert into PRODUCTS values (1502, 'OLYMPUS IS50', 'ELECTRNCS');
10. insert into PRODUCTS values (1600, 'PLAY GYM', 'TOYS');
11. insert into PRODUCTS values (1601, 'LAMAZE', 'TOYS');
12. insert into PRODUCTS values (1666, 'HARRY POTTER', 'DVD');
13. commit;
14.
15. create table NEWPRODUCTS
16. (
17. PRODUCT_ID INTEGER,
18. PRODUCT_NAME VARCHAR2(60),
19. CATEGORY VARCHAR2(60)
20. );
21.
22. insert into NEWPRODUCTS values (1502, 'OLYMPUS CAMERA', 'ELECTRNCS');
23. insert into NEWPRODUCTS values (1601, 'LAMAZE', 'TOYS');
24. insert into NEWPRODUCTS values (1666, 'HARRY POTTER', 'TOYS');
25. insert into NEWPRODUCTS values (1700, 'WAIT INTERFACE', 'BOOKS');
26. commit;
27.
28.1,可省略的update 或者insert
29. MERGE INTO products p
30. 2 USING newproducts np
31. 3 ON (p.product_id = np.product_id)
32. 4 WHEN MATCHED THEN
33. 5 UPDATE
34. 6 SET p.product_name = np.product_name,
35. 7 p.category = np.category;
使用表newproducts中的product_name 和category字段来更新表products 中相同product_id的product_name 和category.
2,当条件不满足的时候把newproducts表中的数据INSERT 到表products中。
1.MERGE INTO products p
2. USING newproducts np
3. ON (p.product_id = np.product_id)
4. WHEN NOT MATCHED THEN
5. INSERT
6. VALUES (np.product_id, np.product_name,
7. np.category);
3,带条件的insert 和update
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. WHERE p.category = np.category;
insert 和update 都带有where 字句
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. p.category = np.category
8. WHERE p.category = 'DVD'
9. WHEN NOT MATCHED THEN
10. INSERT
11. VALUES (np.product_id, np.product_name, np.category)
12. WHERE np.category != 'BOOKS'
4,无条件的insert
1.MERGE INTO products p
2. USING newproducts np
3. ON (1=0)
4. WHEN NOT MATCHED THEN
5. INSERT
6. VALUES (np.product_id, np.product_name, np.category)
7. 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 中的条件,所以没有被删除。!!!!!!重点