最近为了批量操作一批数据。为了方便操作,编写了一个pl/sql的过程,然而在调试的过程中,发现了很多问题。现总结一下其中游标使用的注意事项。
---批量为病人生成医嘱 declare V_orders orders%rowtype ; v_orders_costs orders_costs%rowtype ; v_inp_bill_detail inp_bill_detail%rowtype ; v_patient_id pats_in_hospital.patient_id%Type ; cursor c_patientInfo is select patient_id from pats_in_hospital where patient_id != 'M000150330'; cursor c_orders is select * from orders where patient_id='M000150330'; cursor c_orders_costs is select * from orders_costs where patient_id='M000150330'; cursor c_inp_bill_detail is select * from inp_bill_detail where patient_id='M000150330'; begin open c_patientInfo ; fetch c_patientInfo into v_patient_id ; while c_patientInfo%Found loop open c_orders ; /** 注意事项一:当我们的游标第一次打开的时候,游标的指向是在整个数据集的最前面。所以说这个时候的%FOUND的结果是false,因此,在进行判断之前我们需要先将游标向下移动一个位置,才能够使用%Found进行操作。 **/ fetch c_orders into v_orders ; while c_orders%found loop v_orders.patient_id := v_patient_id; insert into orders values v_orders ; /** 注意事项二:我们之所以将下面的语句放到循环的最下面,就是为了避免第一次进行循环的时候造成数据的丢失,因为放到第一条的时候,我们可能丢失第一条数据。 **/ fetch c_orders into v_orders ; end loop; commit ; close c_orders ; open c_orders_costs ; fetch c_orders_costs into v_orders_costs ; while c_orders_costs%found loop v_orders_costs.patient_id :=v_patient_id ; insert into orders_costs values v_orders_costs ; fetch c_orders_costs into v_orders_costs ; end loop ; commit ; close c_orders_costs ; open c_inp_bill_detail ; fetch c_inp_bill_detail into v_inp_bill_detail ; while c_inp_bill_detail%found loop v_inp_bill_detail.patient_id :=v_patient_id ; insert into inp_bill_detail values v_inp_bill_detail ; fetch c_inp_bill_detail into v_inp_bill_detail ; fetch c_patientInfo into v_patient_id ; end loop ; commit ; close c_inp_bill_detail ; end loop ; commit ; close c_patientInfo ; end ;