小乔 发表于 2018-9-22 08:35:44

Oracle SQL、PLSQL 绝技之多表插入

  假如一个在线电子商务系统,我们现在需要根据订单表体现的消费金额将客户简单分为大中小三类并分别插入到三张表中.

订单表 order (order_id number, cust_id number, amount number);
小客户表 small_cust (cust_id number, tot_amt number);
中客户表 med_cust (cust_id number, tot_amt number);
大客户表 big_cust (cust_id number, tot_amt number);
如果总消费金额小于10000, 则归入小客户;
如果总消费金额大于10000并小于50000,则归入中客户;
如果总消费金额大于50000,则归入大客户;
要实现这个需求,如果我们不知道INSERT ALL/FIRST 的用法,可能会用一段PL/SQL遍历查询订单表返回的游标,然后逐条记录判断客户消费总额来决定插入哪个表,需要分别写三个INSERT语句,这样也可以达到目的,但远没有使用INSERT FIRST简洁和高效。
下面是用INSERT FIRST实现的例子,是不是一目了然?  


[*]    insert first
[*]    when tot_amount < 10000 then
[*]    into small_cust_test
[*]    when tot_amount >=10000 and tot_amountcreate table order_test (order_id number, cust_id number, amount number);
[*]
[*]Table created
[*]
[*]SQL> create table small_cust_test (cust_id number, tot_amt number);
[*]
[*]Table created
[*]
[*]SQL> create table med_cust_test (cust_id number, tot_amt number);
[*]
[*]Table created
[*]
[*]SQL> create table big_cust_test (cust_id number, tot_amt number);
[*]
[*]Table created
[*]
[*]SQL> select * from order_test order by order_id;
[*]
[*]ORDER_ID    CUST_ID   AMOUNT
[*]---------- ---------- ----------
[*]         1       1001       2060
[*]         2       1002      20060
[*]         3       1003      30060
[*]         4       1004      50060
[*]         5       1004      10060
[*]         6       1005   100060
[*]         7       1001       2000
[*]         8       1001       2050
[*]
[*]8 rows selected
[*]
[*]SQL> select cust_id, sum(amount) as tot_amt from order_test group by cust_id;
[*]
[*]   CUST_ID    TOT_AMT
[*]---------- ----------
[*]      1003      30060
[*]      1001       6110
[*]      1002      20060
[*]      1004      60120
[*]      1005   100060
[*]
[*]SQL> select * from small_cust_test;
[*]
[*]   CUST_ID    TOT_AMT
[*]---------- ----------
[*]
[*]SQL> select * from med_cust_test;
[*]
[*]   CUST_ID    TOT_AMT
[*]---------- ----------
[*]
[*]SQL> select * from big_cust_test;
[*]
[*]   CUST_ID    TOT_AMT
[*]---------- ----------
[*]
[*]SQL> insert first
[*]2when tot_amount < 10000 then
[*]3into small_cust_test
[*]4when tot_amount >=10000 and tot_amountselect * from small_cust_test;
[*]
[*]   CUST_ID    TOT_AMT
[*]---------- ----------
[*]      1001       6110
[*]
[*]SQL> select * from med_cust_test;
[*]
[*]   CUST_ID    TOT_AMT
[*]---------- ----------
[*]      1003      30060
[*]      1002      20060
[*]
[*]SQL> select * from big_cust_test;
[*]
[*]   CUST_ID    TOT_AMT
[*]---------- ----------
[*]      1004      60120
[*]      1005   100060
[*]
[*]SQL>


页: [1]
查看完整版本: Oracle SQL、PLSQL 绝技之多表插入