【SQL】根据插入语句条件判断插入哪张表,多表插入,2017年


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


订单表 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条件是否已经满足,后续的条件都会被判断,可能会一次出现多表同时插入。 

 

转自:http://stevex.blog.51cto.com/4300375/1042856

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值