假如一個線上電子商務系統,我們現在需要根據訂單表體現的消費金額將客戶簡單分為大中小三類並分別插入到三張表中.
訂單表 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_amount <50000 then into med_cust_test else into big_cust_test select cust_id,sum(amount) as tot_amount from order_test group by cust_id;
FIRST:表示第一WHEN條件符合後就跳到下條記錄,不再判斷其它WHEN條件。 ALL :表示不管前面的WHEN條件是否已經滿足,後續的條件都會被判斷,可能會一次出現多表同時插入。
樣本完整代碼:
SQL> create 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 查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/database/Oracle/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 2 when tot_amount < 10000 then 3 into small_cust_test 4 when tot_amount >=10000 and tot_amount <50000 then 5 into med_cust_test 6 else 7 into big_cust_test 8 select cust_id,sum(amount) as tot_amount 9 from order_test 10 group by cust_id; 5 rows inserted SQL> select * 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>
本文出自 “力量來源於赤誠的愛!” 部落格,請務必保留此出處http://stevex.blog.51cto.com/4300375/1042856