Cursor for loop in PlSql

while i was studying about cursor for loop i found this statement in the web
"A cursor FOR loop implicitly declares its loop index as a %ROWTYPE record"
for example an emp table contain following columns empno,ename,sal,hiredate,deptno
and let us consider an cursor for loop as
for rec in select empno,sal from emp loop
if cursor for loop declare loop index as a %rowtype our cursor statement should include all the columns and follow the data type compatabulity.
But here our cursor statement includes only few columns,if we use %rowtype we have to select all columns but here we are not doing this.
Can anyone please explain what is happening in cursor for loop?

for loop cursor is also like the simple explicite cursor..
the cursor variable will hold only the columns that are given in select statement of the cursor..
if u declare a cursor as %rowtype, then it should include all the columns of that particular table..
otherwise u should use only %type for each and every column seperately only...

Similar Messages

  • How to optimize the select query that is executed in a cursor for loop?

    Hi Friends,
    I have executed the code below and clocked the times for every line of the code using DBMS_PROFILER.
    CREATE OR REPLACE PROCEDURE TEST
    AS
       p_file_id              NUMBER                                   := 151;
       v_shipper_ind          ah_item.shipper_ind%TYPE;
       v_sales_reserve_ind    ah_item.special_sales_reserve_ind%TYPE;
       v_location_indicator   ah_item.exe_location_ind%TYPE;
       CURSOR activity_c
       IS
          SELECT *
            FROM ah_activity_internal
           WHERE status_id = 30
             AND file_id = p_file_id;
    BEGIN
       DBMS_PROFILER.start_profiler ('TEST');
       FOR rec IN activity_c
       LOOP
          SELECT DISTINCT shipper_ind, special_sales_reserve_ind, exe_location_ind
                     INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
                     FROM ah_item --464000 rows in this table
                    WHERE item_id_edw IN (
                             SELECT item_id_edw
                               FROM ah_item_xref --700000 rows in this table
                              WHERE item_code_cust = rec.item_code_cust
                                AND facility_num IN (
                                       SELECT facility_code
                                         FROM ah_chain_div_facility --17 rows in this table
                                        WHERE chain_id = ah_internal_data_pkg.get_chain_id (p_file_id)
                                          AND div_id = (SELECT div_id
                                                          FROM ah_div --8 rows in this table
                                                         WHERE division = rec.division)));
       END LOOP;
       DBMS_PROFILER.stop_profiler;
    EXCEPTION
       WHEN NO_DATA_FOUND
       THEN
          NULL;
       WHEN TOO_MANY_ROWS
       THEN
          NULL;
    END TEST;The SELECT query inside the cursor FOR LOOP took 773 seconds.
    I have tried using BULK COLLECT instead of cursor for loop but it did not help.
    When I took out the select query separately and executed with a sample value then it gave the results in a flash of second.
    All the tables have primary key indexes.
    Any ideas what can be done to make this code perform better?
    Thanks,
    Raj.

    As suggested I'd try merging the queries into a single SQL. You could also rewrite your IN clauses as JOINs and see if that helps, e.g.
    SELECT DISTINCT ai.shipper_ind, ai.special_sales_reserve_ind, ai.exe_location_ind
               INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
               FROM ah_item ai, ah_item_xref aix, ah_chain_div_facility acdf, ah_div ad
              WHERE ai.item_id_edw = aix.item_id_edw
                AND aix.item_code_cust = rec.item_code_cust
                AND aix.facility_num = acdf.facility_code
                AND acdf.chain_id = ah_internal_data_pkg.get_chain_id (p_file_id)
                AND acdf.div_id = ad.div_id
                AND ad.division = rec.division;ALSO: You are calling ah_internal_data_pkg.get_chain_id (p_file_id) every time. Why not do it outside the loop and just use a variable in the inner query? That will prevent context switching and improve speed.
    Edited by: Dave Hemming on Dec 3, 2008 9:34 AM

  • Replace the following open/fetch/close statements with a cursor FOR loop

    Hi anyone could you please help me,
    I would like to replace the following open/fetch/close statements with a cursor FOR loop.
    Codes are:
    CREATE OR REPLACE PROCEDURE COMOES.orchid_shipment_interface IS
      -- get the com shipment header records
      CURSOR c_com_shphdr ( p_dwn_end_dt DATE ) IS
      SELECT custno client_id
           , plheadno plheadno
           , DECODE(carr_no,'FEDX',lading_no,'UPS',lading_no,carrier_pro_no) tracking_no
           , carr_no||'/'||carr_method carrier_id
           , plantid plant_id
           , carr_no
           , lading_no
           , del_custaddr ship_to_id
           , ol_type cfm_order_type
           , del_custno
           , shipterm    freight_terms
           , del_custattn attn_line
           , custaddr
        FROM com_plhead@com_pricing.world
       WHERE status = '9'
         AND (mod_dat) > p_dwn_end_dt;
      -- get the com shipment address records
      CURSOR c_com_shpadr (p_custaddr VARCHAR2) IS
      SELECT name1 addr_name
           , street1 addr_line1
           , street2 addr_line2
           , city city
           , state state_cd
           , zip zip
           , country country_cd
           , phone work_phone
           , email email1
        FROM com_address@com_pricing.world
       WHERE addr_id = p_custaddr;
      -- get the com shipment detail records
      CURSOR c_com_shpdtl ( p_plheadno NUMBER) IS
      SELECT pll.plheadno pllheadno
           , pll.pllineno ord_line_no
           , pll.ol_no erp_line_no
           , pll.ol_segno
           , pll.fg_id sku
           , pll.qty_shipped ship_qty
           , pll.ordno erp_ord_no
           FROM com_plline@com_pricing.world pll
       WHERE pll.plheadno = p_plheadno
         AND NOT EXISTS (SELECT '1'
                           FROM com_pkg_int_interface@com_pricing.world  cpi
                          WHERE pll.ordno = cpi.ordno
                            AND pll.ol_no = cpi.ol_no);
      -- type declaration
      -- type declaration of com table.
      TYPE t_com_shphdr IS TABLE OF c_com_shphdr%ROWTYPE INDEX BY BINARY_INTEGER;
      TYPE t_orchid_shphdr IS TABLE OF orchid_shipment_hdr_intf%ROWTYPE INDEX BY BINARY_INTEGER;
      TYPE t_com_shpadr IS TABLE OF c_com_shpadr%ROWTYPE INDEX BY BINARY_INTEGER;
      TYPE t_orchid_shpadr IS TABLE OF orchid_shipment_address_intf%ROWTYPE INDEX BY BINARY_INTEGER;
      TYPE t_com_shpdtl IS TABLE OF c_com_shpdtl%ROWTYPE INDEX BY BINARY_INTEGER;
      TYPE t_orchid_shpdtl IS TABLE OF orchid_shipment_dtl_intf%ROWTYPE INDEX BY BINARY_INTEGER;
      lv_company_code       com_customer.business_unit%TYPE;
      lv_erp_ord_no         com_plline.ordno%TYPE;
      lv_actual_ship_date   com_plline.confirm_date%TYPE;
      lv_po_no              com_oline.po_no%TYPE;
      lv_ord_date           com_oline.entrydate%TYPE;
      lv_hdr_batch_ctrl_no  download_batch_info.batch_ctrl_no%TYPE;
      lv_adr_batch_ctrl_no  download_batch_info.batch_ctrl_no%TYPE;
      lv_dtl_batch_ctrl_no  download_batch_info.batch_ctrl_no%TYPE;
      lv_sku_desc           com_salesitem.title%TYPE;
      lv_ord_qty            com_oldelseg.qty%TYPE;
      lr_com_shphdr    t_com_shphdr;
      lr_orchid_shphdr t_orchid_shphdr;
      lr_com_shpadr    t_com_shpadr;
      lr_orchid_shpadr t_orchid_shpadr;
      lr_com_shpdtl    t_com_shpdtl;
      lr_orchid_shpdtl t_orchid_shpdtl;
      -- variable declaration
      ln_shphdr_seq    NUMBER(10):= 0;
      ln_shpadr_seg    NUMBER(10):= 0;
      ln_shpdtl_seq    NUMBER(10):= 0;
      cnt              NUMBER(10):= 0;
      cnt1             NUMBER(10):= 0;
      ld_hdr_dwn_end_dt           download_batch_info.download_end_tstamp%TYPE;
      lc_hdr_dwn_status           download_batch_info.dwn_status%TYPE;
      ld_hdr_download_end_tstamp  DATE;
      ln_hdr_running_seq          NUMBER(10) := 0;
      ld_adr_dwn_end_dt           download_batch_info.download_end_tstamp%TYPE;
      lc_adr_dwn_status           download_batch_info.dwn_status%TYPE;
      ld_adr_download_end_tstamp  DATE;
      ln_adr_running_seg          NUMBER(10) := 0;
      ld_dtl_dwn_end_dt           download_batch_info.download_end_tstamp%TYPE;
      lc_dtl_dwn_status           download_batch_info.dwn_status%TYPE;
      ld_dtl_download_end_tstamp  DATE;
      ln_dtl_running_seq          NUMBER(10) := 0;
    BEGIN
      -- get the batch control number details from batch information table for shipment header
      BEGIN
        SELECT batch_ctrl_no
             , NVL(download_end_tstamp,TO_DATE('01/01/1980','MM/DD/YYYY'))
             , dwn_status
          INTO lv_hdr_batch_ctrl_no
             , ld_hdr_dwn_end_dt
             , lc_hdr_dwn_status
          FROM comoes.download_batch_info
         WHERE download_id = 'ORCHID_SHIPMENT_HDR_INTF';
      EXCEPTION
        WHEN NO_DATA_FOUND THEN
          DBMS_OUTPUT.PUT_LINE (' No Data Found for ORCHID_SHIPMENT_HDR_INTF in Download Batch Info table...!!!');
          RAISE;
        WHEN TOO_MANY_ROWS THEN
          DBMS_OUTPUT.PUT_LINE (' Too Many Rows found for ORCHID_SHIPMENT_HDR_INTF in Download Batch Info table...!!!');
          RAISE;
        WHEN OTHERS THEN
          DBMS_OUTPUT.PUT_LINE (' Following error occured while getting batch control number for ORCHID_SHIPMENT_HDR_INTF in Download Batch Info table...!!!'||SQLERRM);
          RAISE;
      END;
      -- get the batch control number details from batch information table for shipment address
      BEGIN
        SELECT batch_ctrl_no
             , NVL(download_end_tstamp,TO_DATE('01/01/1980','MM/DD/YYYY'))
             , dwn_status
          INTO lv_adr_batch_ctrl_no
             , ld_adr_dwn_end_dt
             , lc_adr_dwn_status
          FROM comoes.download_batch_info
         WHERE download_id = 'ORCHID_SHIPMENT_ADDRESS_INTF';
      EXCEPTION
        WHEN NO_DATA_FOUND THEN
          DBMS_OUTPUT.PUT_LINE (' No Data Found for ORCHID_SHIPMENT_ADDRESS_INTF in Download Batch Info table...!!!');
          RAISE;
        WHEN TOO_MANY_ROWS THEN
          DBMS_OUTPUT.PUT_LINE (' Too Many Rows found for ORCHID_SHIPMENT_ADDRESS_INTF in Download Batch Info table...!!!');
          RAISE;
        WHEN OTHERS THEN
          DBMS_OUTPUT.PUT_LINE (' Following error occured while getting batch control number for ORCHID_SHIPMENT_ADDRESS_INTF in Download Batch Info table...!!!'||SQLERRM);
          RAISE;
      END;
      -- get the batch control number details from batch information table for shipment details
      BEGIN
        SELECT batch_ctrl_no
             , NVL(download_end_tstamp,TO_DATE('01/01/1980','MM/DD/YYYY'))
             , dwn_status
          INTO lv_dtl_batch_ctrl_no
             , ld_dtl_dwn_end_dt
             , lc_dtl_dwn_status
          FROM download_batch_info
         WHERE download_id = 'ORCHID_SHIPMENT_DTL_INTF';
      EXCEPTION
        WHEN NO_DATA_FOUND THEN
          DBMS_OUTPUT.PUT_LINE (' No Data Found for ORCHID_SHIPMENT_DTL_INTF in Download Batch Info table...!!!');
          RAISE;
        WHEN TOO_MANY_ROWS THEN
          DBMS_OUTPUT.PUT_LINE (' Too Many Rows found for ORCHID_SHIPMENT_DTL_INTF in Download Batch Info table...!!!');
          RAISE;
        WHEN OTHERS THEN
          DBMS_OUTPUT.PUT_LINE (' Following error occured while getting batch control number for ORCHID_SHIPMENT_DTL_INTF in Download Batch Info table...!!!'||SQLERRM);
          RAISE;
      END;
      -- if previous run is not sucess then do nothing and return.
      OPEN c_com_shphdr ( ld_hdr_dwn_end_dt ) ;
      LOOP
        -- delete the collection for every cycle
        lr_com_shphdr.DELETE;
        lr_orchid_shphdr.DELETE;
        lr_com_shpadr.DELETE;
        lr_orchid_shpadr.DELETE;
        lr_com_shpdtl.DELETE;
        lr_orchid_shpdtl.DELETE;
        -- fetch the order header records to collection
        FETCH c_com_shphdr BULK COLLECT INTO lr_com_shphdr LIMIT 500;
        -- where there is no record in the collection the exit from the loop
        EXIT WHEN lr_com_shphdr.COUNT = 0;
        -- build your logic there to populate the data into order header collection.
          FOR i IN 1..lr_com_shphdr.COUNT
          LOOP
            -- accumulate header running sequence number
            ln_hdr_running_seq := ln_hdr_running_seq + 1;
            ln_shphdr_seq      := ln_hdr_running_seq;
             -- Get the business unit for the customer from com_customer
            BEGIN
              SELECT business_unit
                INTO lv_company_code
                FROM com_customer@com_pricing.world
               WHERE custno = lr_com_shphdr(i).del_custno;
            EXCEPTION
            WHEN OTHERS THEN
              lv_company_code := NULL;
            END;
            -- Get the ordno, confirm_date from COM_PLLINE
            BEGIN
            SELECT ordno
                 , confirm_date
              INTO lv_erp_ord_no
                 , lv_actual_ship_date
              FROM com_plline@com_pricing.world cpl
             WHERE cpl.plheadno = lr_com_shphdr(i).plheadno
               AND ROWNUM = 1;
            EXCEPTION
            WHEN OTHERS THEN
              lv_erp_ord_no       := NULL;
              lv_actual_ship_date := NULL;
            END;
            -- Get the po_no, Entry_date from COM_OLINE
            BEGIN
              SELECT po_no
                   , entrydate
                INTO lv_po_no
                   , lv_ord_date
                FROM com_oline@com_pricing.world col
               WHERE col.ordno = lv_erp_ord_no
                 AND ROWNUM = 1;
            EXCEPTION
            WHEN OTHERS THEN
              lv_po_no    := NULL;
              lv_ord_date := NULL;
            END;
            -- To assign the Bol Number from Lading Number
            IF lr_com_shphdr(i).carr_no NOT IN ('FEDX','UPS') THEN
               lr_orchid_shphdr(i).bol_no     := lr_com_shphdr(i).lading_no;
            ELSE
               lr_orchid_shphdr(i).bol_no     := NULL;
            END IF;
            -- For each order header get the Shipment Delivery Adderss
            OPEN c_com_shpadr ( lr_com_shphdr(i).custaddr);
            FETCH c_com_shpadr BULK COLLECT INTO lr_com_shpadr;
            -- where there is no record in the collection the exit from the loop
            EXIT WHEN lr_com_shpadr.COUNT = 0;
            -- biuld your logic here to populate the del address collection.
              FOR j IN 1..lr_com_shpadr.COUNT
              LOOP
                -- accumulate the loop count into temp variable, so that will through tell each set of order header.
                cnt := cnt + 1;
                -- accumolate the header running sequence number.
                ln_adr_running_seg := ln_adr_running_seg + 1;
                ln_shpadr_seg := ln_adr_running_seg;
                -- move the order address data into collection.
                lr_orchid_shpadr(cnt).client_id       := lr_com_shphdr(i).del_custno;
                lr_orchid_shpadr(cnt).ord_no          := lr_com_shphdr(i).plheadno;
                lr_orchid_shpadr(cnt).tracking_no     := lr_com_shphdr(i).tracking_no;
                lr_orchid_shpadr(cnt).addr_name       := lr_com_shpadr(j).addr_name;
                lr_orchid_shpadr(cnt).attn_line       := lr_com_shphdr(i).attn_line;
                lr_orchid_shpadr(cnt).addr_line1      := lr_com_shpadr(j).addr_line1;
                lr_orchid_shpadr(cnt).addr_line2      := lr_com_shpadr(j).addr_line2;
                lr_orchid_shpadr(cnt).addr_line3      := NULL;
                lr_orchid_shpadr(cnt).addr_line4      := NULL;
                lr_orchid_shpadr(cnt).addr_line5      := NULL;
                lr_orchid_shpadr(cnt).city            := lr_com_shpadr(j).city;
                lr_orchid_shpadr(cnt).state_cd        := lr_com_shpadr(j).state_cd;
                lr_orchid_shpadr(cnt).zip             := lr_com_shpadr(j).zip;
                lr_orchid_shpadr(cnt).zip_ext         := NULL;
                lr_orchid_shpadr(cnt).country_cd      := lr_com_shpadr(j).country_cd;
                lr_orchid_shpadr(cnt).tax_geo_cd      := NULL;
                lr_orchid_shpadr(cnt).work_phone      := lr_com_shpadr(j).work_phone;
                lr_orchid_shpadr(cnt).email1          := lr_com_shpadr(j).email1;
                lr_orchid_shpadr(cnt).cre_dat         := SYSDATE;
                lr_orchid_shpadr(cnt).cre_usr         := USER;
                lr_orchid_shpadr(cnt).batch_ctrl_no   := lv_adr_batch_ctrl_no;
              END LOOP;
            CLOSE c_com_shpadr;
            -- For each order header get the order detail/delivery segment data
            OPEN c_com_shpdtl ( lr_com_shphdr(i).plheadno );
            FETCH c_com_shpdtl BULK COLLECT INTO lr_com_shpdtl;
            -- where there is no record in the collection the exit from the loop
            EXIT WHEN lr_com_shpdtl.COUNT = 0;
            -- build your logic here to populate the order detail collection
              FOR k IN 1..lr_com_shpdtl.COUNT
              LOOP
                -- accumulate the loop count into a temp variable, so that will through till each set of Order Header.
                cnt1 := cnt1 + 1;
                -- accumulate header running sequence number
                ln_dtl_running_seq := ln_dtl_running_seq + 1;
                ln_shpdtl_seq := ln_dtl_running_seq;
                -- Get Quantity for the delvery from delevery segment table.
                BEGIN
                  SELECT NVL(Qty,0)
                    INTO lv_ord_qty
                    FROM com_oldelseg@com_pricing.world cds
                   WHERE cds.ordno = lr_com_shpdtl(k).erp_ord_no
                     AND cds.ol_no = lr_com_shpdtl(k).erp_line_no
                     AND cds.ol_segno = lr_com_shpdtl(k).ol_segno;
                EXCEPTION
                  WHEN OTHERS THEN
                    lv_ord_qty := NULL;
                END;
                -- Get Title for the salesitem from the salesitem table.
                BEGIN
                  SELECT Title
                    INTO lv_sku_desc
                    FROM com_salesitem@com_pricing.world cs
                   WHERE cs.fg_id = lr_com_shpdtl(k).sku;
                EXCEPTION
                  WHEN OTHERS THEN
                    lv_sku_desc := NULL;
                END;
                -- move the Order detail data into collection
                lr_orchid_shpdtl(cnt1).client_id         := lr_com_shphdr(i).client_id;
                lr_orchid_shpdtl(cnt1).ord_no            := lr_com_shphdr(i).plheadno;
                lr_orchid_shpdtl(cnt1).ord_line_no       := lr_com_shpdtl(k).ord_line_no;
                lr_orchid_shpdtl(cnt1).erp_line_no       := lr_com_shpdtl(k).erp_line_no;
                lr_orchid_shpdtl(cnt1).sku               := lr_com_shpdtl(k).sku;
                lr_orchid_shpdtl(cnt1).tracking_no       := lr_com_shphdr(i).tracking_no;
                lr_orchid_shpdtl(cnt1).container_no      := NULL;
                lr_orchid_shpdtl(cnt1).ord_qty           := lv_ord_qty;
                lr_orchid_shpdtl(cnt1).ship_qty          := lr_com_shpdtl(k).ship_qty;
                lr_orchid_shpdtl(cnt1).price_point       := NULL;
                lr_orchid_shpdtl(cnt1).pick_invoice_no   := NULL;
                lr_orchid_shpdtl(cnt1).cancel_qty        := NULL;
                lr_orchid_shpdtl(cnt1).bldg_id           := NULL;                              --lr_com_shpdtl(k).bldg_id;
                lr_orchid_shpdtl(cnt1).sku_company       := NULL;                              --lr_com_shpdtl(k).sku_company;
                lr_orchid_shpdtl(cnt1).sku_desc          := lv_sku_desc;
                lr_orchid_shpdtl(cnt1).icc_cd1           := NULL;                              --lr_com_shpdtl(k).icc_cd1;
                lr_orchid_shpdtl(cnt1).erp_ord_no        := lr_com_shpdtl(k).erp_ord_no;
                lr_orchid_shpdtl(cnt1).cre_dat           := SYSDATE;
                lr_orchid_shpdtl(cnt1).cre_usr           := USER;
                lr_orchid_shpdtl(cnt1).batch_ctrl_no     := lv_dtl_batch_ctrl_no;
              END LOOP;
            CLOSE c_com_shpdtl;
            -- build the logic to populate Order Header
            lr_orchid_shphdr(i).client_id              := lr_com_shphdr(i).client_id;
            lr_orchid_shphdr(i).ord_no                 := lr_com_shphdr(i).plheadno;
            lr_orchid_shphdr(i).tracking_no            := lr_com_shphdr(i).tracking_no;
            lr_orchid_shphdr(i).container_no           := NULL;                            -- container number is not maintained in COM
            lr_orchid_shphdr(i).carrier_id             := lr_com_shphdr(i).carrier_id;
            lr_orchid_shphdr(i).plant_id               := lr_com_shphdr(i).plant_id;
            lr_orchid_shphdr(i).erp_ord_no             := lv_erp_ord_no;
            lr_orchid_shphdr(i).erp_ord_no2            := NULL;
            lr_orchid_shphdr(i).po_no                  := lv_po_no;
            lr_orchid_shphdr(i).ship_to_id             := lr_com_shphdr(i).ship_to_id;
            lr_orchid_shphdr(i).ship_to_addr_id        := lr_com_shphdr(i).custaddr;
            lr_orchid_shphdr(i).scac                   := NULL;                             --lr_com_shphdr(i).scac;
            lr_orchid_shphdr(i).actual_ship_date       := lv_actual_ship_date;
            lr_orchid_shphdr(i).cfm_order_type         := lr_com_shphdr(i).cfm_order_type;
            lr_orchid_shphdr(i).company_code           := lv_company_code;
            lr_orchid_shphdr(i).no_of_order_lines      := NULL;                             --lr_com_shphdr(i).no_of_order_lines;
            lr_orchid_shphdr(i).pick_invoice_no        := NULL;
            lr_orchid_shphdr(i).ord_date               := lv_ord_date;
            lr_orchid_shphdr(i).orig_tender_date       := NULL;
            lr_orchid_shphdr(i).orig_delv_date         := NULL;
            lr_orchid_shphdr(i).delivery_flag          := NULL;
            lr_orchid_shphdr(i).delv_date_from         := NULL;
            lr_orchid_shphdr(i).delv_date_to           := NULL;
            lr_orchid_shphdr(i).orig_carr_cd           := NULL;
            lr_orchid_shphdr(i).routing_comment        := NULL;
            lr_orchid_shphdr(i).segment_type           := NULL;
            lr_orchid_shphdr(i).back_order_flag        := NULL;
            lr_orchid_shphdr(i).addr_override_flag     := NULL;
            lr_orchid_shphdr(i).fmx_assigned_carr      := NULL;
            lr_orchid_shphdr(i).fmx_assigned_ship_date := NULL;
            lr_orchid_shphdr(i).fmx_assigned_delv_date := NULL;
            lr_orchid_shphdr(i).freight_terms          := lr_com_shphdr(i).freight_terms;
            lr_orchid_shphdr(i).fmx_load_id            := NULL;
            lr_orchid_shphdr(i).asn_type               := NULL;
            lr_orchid_shphdr(i).icc_cd1                := NULL;                             --lr_com_shphdr(i).icc_cd1;
            lr_orchid_shphdr(i).trans_type             := NULL;
            lr_orchid_shphdr(i).ref_no1                := NULL;
            lr_orchid_shphdr(i).ref_no2                := NULL;
            lr_orchid_shphdr(i).ref_no3                := NULL;
            lr_orchid_shphdr(i).ref_no4                := NULL;
            lr_orchid_shphdr(i).cre_dat                := SYSDATE;
            lr_orchid_shphdr(i).cre_usr                := USER;
            lr_orchid_shphdr(i).batch_ctrl_no          := lv_hdr_batch_ctrl_no;
            -- logic to get total boxes and weight.
            BEGIN
              SELECT SUM(no_cartons), SUM(weight)
                INTO lr_orchid_shphdr(i).total_boxes
                   , lr_orchid_shphdr(i).weight
                FROM com_plline@com_pricing.world pll
               WHERE pll.plheadno = lr_com_shphdr(i).plheadno;
            EXCEPTION
             WHEN OTHERS THEN
                lr_orchid_shphdr(i).total_boxes := NULL;
                lr_orchid_shphdr(i).weight      := NULL;
            END;
          END LOOP;
        -- initialize the variables for next loop cycle.
        cnt := 0;
        cnt1 := 0;
        -- populate the shipment header interface table.
        FOR x IN 1..lr_orchid_shphdr.COUNT
        LOOP
          ld_hdr_download_end_tstamp := lr_orchid_shphdr(x).cre_dat;
          INSERT INTO orchid_shipment_hdr_intf
                    (record_qualifier
                    ,client_id
                    ,ord_no
                    ,tracking_no
                    ,container_no
                    ,bol_no
                    ,carrier_id
                    ,plant_id
                    ,erp_ord_no
                    ,erp_ord_no2
                    ,po_no
                    ,ship_to_id
                    ,ship_to_addr_id
                    ,scac
                    ,actual_ship_date
                    ,cfm_order_type
                    ,company_code
                    ,no_of_order_lines
                    ,pick_invoice_no
                    ,total_boxes
                    ,weight
                    ,ord_date
                    ,orig_tender_date
                    ,orig_delv_date
                    ,delivery_flag
                    ,delv_date_from
                    ,delv_date_to
                    ,orig_carr_cd
                    ,routing_comment
                    ,segment_type
                    ,back_order_flag
                    ,addr_override_flag
                    ,fmx_assigned_carr
                    ,fmx_assigned_ship_date
                    ,fmx_assigned_delv_date
                    ,freight_terms
                    ,fmx_load_id
                    ,asn_type
                    ,upl_status
                    ,icc_cd1
                    ,trans_type
                    ,ref_no1
                    ,ref_no2
                    ,ref_no3
                    ,ref_no4
                    ,cre_dat
                    ,cre_usr
                    ,batch_ctrl_no)
            VALUES
                    ( 10
                    ,lr_orchid_shphdr(x).client_id
                    ,lr_orchid_shphdr(x).ord_no
                    ,lr_orchid_shphdr(x).tracking_no
                    ,lr_orchid_shphdr(x).container_no
                    ,lr_orchid_shphdr(x).bol_no
                    ,lr_orchid_shphdr(x).carrier_id
                    ,lr_orchid_shphdr(x).plant_id
                    ,lr_orchid_shphdr(x).erp_ord_no
                    ,lr_orchid_shphdr(x).erp_ord_no2
                    ,lr_orchid_shphdr(x).po_no
                    ,lr_orchid_shphdr(x).ship_to_id
                    ,lr_orchid_shphdr(x).ship_to_addr_id
                    ,lr_orchid_shphdr(x).scac
                    ,lr_orchid_shphdr(x).actual_ship_date
                    ,lr_orchid_shphdr(x).cfm_order_type
                    ,lr_orchid_shphdr(x).company_code
                    ,lr_orchid_shphdr(x).no_of_order_lines
                    ,lr_orchid_shphdr(x).pick_invoice_no
                    ,lr_orchid_shphdr(x).total_boxes
                    ,lr_orchid_shphdr(x).weight
                    ,lr_orchid_shphdr(x).ord_date
                    ,lr_orchid_shphdr(x).orig_tender_date
                    ,lr_orchid_shphdr(x).orig_delv_date
                    ,lr_orchid_shphdr(x).delivery_flag
                    ,lr_orchid_shphdr(x).delv_date_from
                    ,lr_orchid_shphdr(x).delv_date_to
                    ,lr_orchid_shphdr(x).orig_carr_cd
                    ,lr_orchid_shphdr(x).routing_comment
                    ,lr_orchid_shphdr(x).segment_type
                    ,lr_orchid_shphdr(x).back_order_flag
                    ,lr_orchid_shphdr(x).addr_override_flag
                    ,lr_orchid_shphdr(x).fmx_assigned_carr
                    ,lr_orchid_shphdr(x).fmx_assigned_ship_date
                    ,lr_orchid_shphdr(x).fmx_assigned_delv_date
                    ,lr_orchid_shphdr(x).freight_terms
                    ,lr_orchid_shphdr(x).fmx_load_id
                    ,lr_orchid_shphdr(x).asn_type
                    ,00
                    ,lr_orchid_shphdr(x).icc_cd1
                    ,lr_orchid_shphdr(x).trans_type
                    ,lr_orchid_shphdr(x).ref_no1
                    ,lr_orchid_shphdr(x).ref_no2
                    ,lr_orchid_shphdr(x).ref_no3
                    ,lr_orchid_shphdr(x).ref_no4
                    ,lr_orchid_shphdr(x).cre_dat
                    ,lr_orchid_shphdr(x).cre_usr
                    ,lr_orchid_shphdr(x).batch_ctrl_no);
        END LOOP;
        -- populate the shipment address interface table.
        FOR y IN 1..lr_orchid_shpadr.COUNT
        LOOP
          ld_adr_download_end_tstamp := lr_orchid_shpadr(y).cre_dat;
          INSERT INTO orchid_shipment_address_intf
                      ( record_qualifier
                      , client_id
                      , ord_no
                      , tracking_no
                      , addr_name
                      , attn_line
                      , addr_line1
                      , addr_line2
                      , addr_line3
                      , addr_line4
                      , addr_line5
                      , city
                      , state_cd
                      , zip
                      , zip_ext
                      , country_cd
                      , tax_geo_cd
                      , work_phone
                      , email1
                      , cre_dat
                      , cre_usr
                      , batch_ctrl_no)
               VALUES ( 14
                      , lr_orchid_shpadr(y).client_id
                      , lr_orchid_shpadr(y).ord_no
                      , lr_orchid_shpadr(y).tracking_no
                      , lr_orchid_shpadr(y).addr_name
                      , lr_orchid_shpadr(y).attn_line
                      , lr_orchid_shpadr(y).addr_line1
                      , lr_orchid_shpadr(y).addr_line2
                      , lr_orchid_shpadr(y).addr_line3
                      , lr_orchid_shpadr(y).addr_line4
                      , lr_orchid_shpadr(y).addr_line5
                      , lr_orchid_shpadr(y).city
                      , lr_orchid_shpadr(y).state_cd
                      , lr_orchid_shpadr(y).zip
                      , lr_orchid_shpadr(y).zip_ext
                      , lr_orchid_shpadr(y).country_cd
                      , lr_orchid_shpadr(y).tax_geo_cd
                      , lr_orchid_shpadr(y).work_phone
                      , lr_orchid_shpadr(y).email1
                      , lr_orchid_shpadr(y).cre_dat
                      , lr_orchid_shpadr(y).cre_usr
                      , lr_orchid_shpadr(y).batch_ctrl_no);
        END LOOP;
        -- populate the shipment detail interface table.
        FOR z IN 1..lr_orchid_shpdtl.COUNT
        LOOP
          ld_dtl_download_end_tstamp := lr_orchid_shpdtl(z).cre_dat;
          INSERT INTO orchid_shipment_dtl_intf
                      ( record_qualifier
                      , client_id
                      , ord_no
                      , ord_line_no
                      , erp_line_no
                      , sku
                      , tracking_no
                      , container_no
                      , ord_qty
                      , ship_qty
                      , price_point
                      , pick_invoice_no
                      , cancel_qty
                      , bldg_id
                      , sku_company
                      , sku_desc
                      , icc_cd1
                      , erp_ord_no
                      , cre_dat
                      , cre_usr
                      , batch_ctrl_no)
               VALUES ( 20
                      , lr_orchid_shpdtl(z).client_id
                      , lr_orchid_shpdtl(z).ord_no
                      , lr_orchid_shpdtl(z).ord_line_no
                      , lr_orchid_shpdtl(z).erp_line_no
                      , lr_orchid_shpdtl(z).sku
                      , lr_orchid_shpdtl(z).tracking_no
                      , lr_orchid_shpdtl(z).container_no
                      , lr_orchid_shpdtl(z).ord_qty
                      , lr_orchid_shpdtl(z).ship_qty
                      , lr_orchid_shpdtl(z).price_point
                      , lr_orchid_shpdtl(z).pick_invoice_no
                      , lr_orchid_shpdtl(z).cancel_qty
                      , lr_orchid_shpdtl(z).bldg_id
                      , lr_orchid_shpdtl(z).sku_company
                      , lr_orchid_shpdtl(z).sku_desc
                      , lr_orchid_shpdtl(z).icc_cd1
                      , lr_orchid_shpdtl(z).erp_ord_no
                      , lr_orchid_shpdtl(z).cre_dat
                      , lr_orchid_shpdtl(z).cre_usr
                      , lr_orchid_shpdtl(z).batch_ctrl_no);
        END LOOP;
        COMMIT;
      END LOOP;
      CLOSE c_com_shphdr;
      -- set the status to success
      UPDATE comoes.download_batch_info
         SET batch_ctrl_no = orchid_plhead_btch_ctrl_seq.NEXTVAL
           , dwn_status = '90'
           , download_end_tstamp = NVL(ld_hdr_download_end_tstamp,SYSDATE)
       WHERE download_id = 'ORCHID_SHIPMENT_HDR_INTF'
         AND batch_ctrl_no = lv_hdr_batch_ctrl_no;
      UPDATE comoes.download_batch_info
         SET batch_ctrl_no = orchid_address_btch_ctrl_seq.NEXTVAL
           , dwn_status = '90'
           , download_end_tstamp = NVL(ld_hdr_download_end_tstamp,SYSDATE)
       WHERE download_id = 'ORCHID_SHIPMENT_ADDRESS_INTF'
         AND batch_ctrl_no = lv_adr_batch_ctrl_no;
      UPDATE comoes.download_batch_info
         SET batch_ctrl_no = orchid_plline_btch_ctrl_seq.NEXTVAL
           , dwn_status = '90'
           , download_end_tstamp = NVL(ld_dtl_download_end_tstamp,SYSDATE)
       WHERE download_id = 'ORCHID_SHIPMENT_DTL_INTF'
         AND batch_ctrl_no = lv_dtl_batch_ctrl_no;
      -- Update the download status to success in the interface table.
      -- Shipment Header
      COMMIT;
    EXCEPTION
      WHEN OTHERS THEN
        -- load is not sucess then set the status to fail
        UPDATE comoes.download_batch_info
           SET dwn_status = '99'
         WHERE download_id = 'ORCHID_SHIPMENT_HDR_INTF'
           AND batch_ctrl_no = lv_hdr_batch_ctrl_no;
        UPDATE comoes.download_batch_info
           SET dwn_status = '99'
         WHERE download_id = 'ORCHID_SHIPMENT_ADDRESS_INTF'
           AND batch_ctrl_no = lv_adr_batch_ctrl_no;
        UPDATE comoes.download_batch_info
           SET dwn_status = '99'
         WHERE download_id = 'ORCHID_SHIPMENT_DTL_INTF'
           AND batch_ctrl_no = lv_dtl_batch_ctrl_no;
        COMMIT;
        DBMS_OUTPUT.PUT_LINE('Following error occured while executing ORCHID_SHIPMENT_INTF procedure...!!!'||SQLERRM);
        RAISE;
    END orchid_shipment_interface;Edited by: BluShadow on 03-Aug-2011 13:28
    added {noformat}{noformat} tags. Please read {message:id=9360002} to learn to do this yourself.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                &nb

    Please read the Forum FAQ on how to ask a question, particularly how to format code
    SQL and PL/SQL FAQ
    SQL and PL/SQL FAQ
    WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE (' Following error occured while getting batch control number for ORCHID_SHIPMENT_HDR_INTF in Download Batch Info table...!!!'||SQLERRM);
    RAISE;http://tkyte.blogspot.com/2008/01/why-do-people-do-this.html

  • PL/SQL block to create temporary table + load via cursor for loop

    Assume I have a table that contains a subset of data that I want to load into a temporary table within a cursor for-loop. Is it possible to have a single statement to create the table and load based on the results of the fetch?
    I was thinking something like:
    Declare CURSOR xyz is
    CREATE TABLE temp_table as
    select name, rank, serial number from
    HR table where rank = 'CAPTAIN'
    BEGIN
    OPEN xyz
    for name in xyz
    LOOP
    END LOOP
    What I see wrong with this is that the table would be created multiple times which is why this syntax is not acceptable. I'd prefer not to have to define the temporary table then load in two sepearte SQL statements and am hoping a single statement can be used.
    Thanks!

    What is the goal here?
    If you're just going to iterate over the rows that are returned in a cursor, a temporary table is unnecessary and only adds complexity. If you truly need a temporary table, you would declare it exactly once, at install time when you create all your other tables. You'd INSERT data into the temp table and the data would only be visible to the session that inserted it.
    Justin

  • Commit after every three UPDATEs in CURSOR FOR loop

    DB Version: 11g
    I know that experts in here despise the concept of COMMITing inside loop.
    But most of the UPDATEs being fired by the code below are updating around 1 million records and it is breaking our UNDO tablespace.
    begin
    for rec in
          (select owner,table_name,column_name 
          from dba_tab_cols where column_name like 'ABCD%' and owner = p_schema_name)
          loop
            begin
            execute immediate 'update '||rec.owner||'.'||rec.table_name||' set '||rec.column_name|| ' = '''||rec.owner||'';
            end;
          end loop;
    end;We are not expecting ORA-01555 error as these are just batch updates.
    I was thinking of implementing something like
    FOR i IN 1..myarray.count
    LOOP
                             DBMS_OUTPUT.PUT_LINE('event_key at' || i || ' is: ' || myarray(i));
                             INSERT INTO emp
                             empid,
                             event_id,
                             dept,
                             event_key
                             VALUES
                             v_empid,
                             3423,
                             p_dept,
                             myarray(i)
                             if(MOD(i, p_CommitFreq) = 0)  --- When the loop counter becomes fully divisible by p_commit_frequency, it COMMITs
                             then
                                       commit;
                             end if;
    END LOOP;(Found from an OTN thread)
    But i don't know how to access the loop counter value in a CURSOR FOR loop.

    To be fair, what is really despised is code that takes an operation that could have been performed in a single SQL statement and steps through it in the slowest possible way, committing pointlessly as it goes along (exactly like the example you found). Your original version doesn't do that - it looks more like some sort of one-off migration where you have to set every value of every column that matches some naming standard pattern to a constant. If that's the case, and if there are huge volumes involved and you can't simply add a bit more undo, then I don't see much wrong with committing after each update, especially if you track how far you've got so you can restart cleanly if it fails.
    If you really want an incrementing counter in an unnamed cursor, apart from the explicit variable others have suggested, you could add rownum to the cursor (alias it to something that isn't an Oracle keyword), although it could complicate the ORDER BY that you might be considering for the restart logic. You could have that instead of the redundant 'owner' column in your example which is always the same as the constant p_schema_name.
    Another approach would be to keep track of SQL%ROWCOUNT after each update by adding it to a variable, and commit when the total number of rows updated so far reaches, say, a million.
    Could the generated statement use a WHERE clause, or does it really have to update every row in every table it finds?
    Could there be more than one column to update per table? If so it might be worth generating one multi-column update statement per table, although it'll complicate things a bit.
    btw you don't need the inner 'begin' and 'end' keywords, and whoever supplied the MOD example you found should know that three or four spaces usually make a good indent and you don't need brackets around IF conditions.

  • Cursor for loop vs bind variable efficiency

    PL/SQL
    I am going to need to execute many sqls within a cursor for loop.
    Note: This is pseudo pl/sql code
    for csr_rec in cursor
    loop
    insert into tablea
    select [whateever] from tableb
    where column_name = csr_rec.field
    versus
    execute immediate
    'insert into table a select ... where column_name = :1' using csr_rec.field
    So the question is whether the first insert statement will be treated as a separate sql statement and need to be parsed each iteration? If so, then I'd likely be much better of using the bind variable approach. (2nd) insert statement.
    Thanks!

    The first statement (static) will be re-used - PL/SQL variables (csr_rec.field in this case) will be used as a bind variable.

  • Cursor For Loop SQL/PL right application? Need help with PL Performance

    I will preface this post by saying that I am a novice Oracle PL user, so an overexplanation would not be an issue here.
    Goal: Run a hierarchial query for over 120k rows and insert output into Table 1. Currently I am using a Cursor For Loop that takes the first record and puts 2 columns in "Start" section and "connect by" section. The hierarchial query runs and then it inserts the output into another table. I do this 120k times( I know it's not very efficient). Now the hierarchial query doesn't take too long ( run by itself for many parts) but this loop process is taking over 9 hrs to run all 120k records. I am looking for a way to make this run faster. I've read about "Bulk collect" and "forall", but I am not understanding how they function to help me in my specific case.
    Is there anyway I can rewrite the PL/SQL Statement below with the Cursor For loop or with another methodology to accomplish the goal significantly quicker?
    Below is the code ( I am leaving some parts out for space)
    CREATE OR REPLACE PROCEDURE INV_BOM is
    CURSOR DISPATCH_CSR IS
    select materialid,plantid
    from INV_SAP_BOM_MAKE_UNIQUE;
    Begin
    For Row_value in Dispatch_CSR Loop
    begin
    insert into Table 1
    select column1
    ,column2
    ,column3
    ,column4
    from( select ..
    from table 3
    start with materialid = row_value.materialid
    and plantid = row_value.plantid
    connect by prior plantid = row.value_plantid
    exception...
    end loop
    exception..
    commit

    BluShadow:
    The table that the cursor is pulling from ( INV_SAP_BOM_MAKE_UNIQUE) has only 2 columns
    Materialid and Plantid
    Example
    Materialid Plantid
    100-C 1000
    100-B 1010
    X-2 2004
    I use the cursor to go down the list 1 by 1 and run a hierarchical query for each row. The only reason I do this is because I have 120,000 materialid,plantid combinations that I need to run and SQL has a limit of 1000 items in the "start with" if I'm semi-correct on that.
    Structure of Table it would be inserted into ( Table 1) after Hierarchical SQL Statement runs:
    Materialid Plantid User Create Column1 Col2
    100-C 1000 25 EA
    The Hierarchical query ran gives the 2 columns at the end.
    I am looking for a way to either just run a quicker SQL or a more efficient way of running all 120,000 materialid, plantid rows through the Hierarchial Query.
    Any Advice? I really appreciate it. Thank You.

  • Problem in executing cursor for loop

    hi all,
    I am facing following problem.
    We are using cron utility on unix to run pl/sql stored procedure.
    This procedure in turn calls separate procedures. However any one of the procedure does not end in pl/sql even though it has completed its intended processing.
    We are using cursor for loop for data processing and also using database link to fetch data from other instance.
    Can anyone help me on possible reasons for this problem

    The proc only needs a single 'open s_cursor for ...' statement where the query is a join between all the tables involved. You have obfuscated your query so much in the post that I can't construct it for you (your second select doesn't even join to the 's' table), but the point is that you don't need a cursor loop, just a single query.

  • Urgent help in cursor for loop. PLS HELP HELP HEP

    suppose i got table_a, in table_a i've got abc_id and bcd_name. the data as below:
    abc_id bcd_name
    1 a
    1 b
    1 c
    1 d
    in stored procedure as the statement below, i can only select 1 record into a local variable:
    select bcd_name
    into l_bcd_name
    where abc_id = i_abc_id;
    how am i going to select all the records? i know it's going to use a cursor for-loop statement but i dont know how to use. any1 can help?
    Message was edited by:
    babyekc

    Hi,
    You can do like this.
    Just write the following code in ur Stored Procedure.
    CURSOR C1 IS SELECT ABC_ID, BCD_NAME FROM TABLE_A;
    BEGIN
    OPEN C1;
    LOOP
    FETCH C1 INTO TEMP_ABCID, TEMP_BCDNAME;
    EXIT WHEN C1%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE('ABC ID is ' || TEMP_ABCID);
    DBMS_OUTPUT.PUT_LINE('BCD NAME is ' || TEMP_BCD_NAME);
    END LOOP;
    CLOSE C1;
    END;
    Before declaring the cursor, declare the variables TEMP_ABCID, TEMP_BCDNAME.
    Thanks.

  • Cursor for loop gives less number of records for certain condition

    Hi i am getting very weired behaviour of cursor for loop.
    i have one query below which returns 128 records.
    select su.item_id from suv_tmp su
    inner join review_items ri on su.ITEM_ID = RI.ITEM_ID
    inner join sources s on s.source_id=ri.source_id
    and s.source_name='XYZ'
    but when i take this query in cursor for loop it returns only 100 records.
    this is the cursor for loop i am writing:
    begin
    for v_rec in
    (select su.item_id from suv_tmp su
    inner join review_items ri on su.ITEM_ID = RI.ITEM_ID
    inner join sources s on s.source_id=ri.source_id
    where s.source_name='XYZ'
    loop
    dbms_output.put_line(v_rec.item_id);
    end loop;
    end;
    It prints only 100 records.
    The weired behaviour is that if i select any column name from the table which is used in where clause it gives 128 records..
    query below gives expected output
    begin
    for v_rec in
    (select su.item_id,s.source_descr from suv_tmp su
    inner join review_items ri on su.ITEM_ID = RI.ITEM_ID
    inner join sources s on s.source_id=ri.source_id
    where s.source_name='XYZ'
    loop
    dbms_output.put_line(v_rec.item_id);
    end loop;
    end;
    i am not able to find out any logc..
    Any pointers appreciated..
    Edited by: user11266153 on Dec 14, 2011 11:27 PM

    1) Can you provide the DDLs of those tables and dummy data to check if it gets reproduced at our env.
    2) What is the Oracle Database software version? e.g. 9iR2 , 10gR1 , 10gR2 , 11gR1 etc...

  • Is this another form of a cursor for loop?

    Hi,
    I'm working, in Oracle 10gR2 in Windows XP, on a stored procedure that was given to me mostly completed and I'm trying to decypher the syntax of the cursor.
    CREATE OR REPLACE PROCEDURE p_proc1(p_from_date IN DATE
                                                        ,p_to_date   IN DATE
                                                        ,p_result_cur   IN OUT dbo.pkg_q.ref_cursor) IS
    BEGIN
        OPEN ,p_result_cur FOR WITH wr AS(
            SELECT wr.F1
                  ,wr.F2
                  ,wr.F3
                  ,wr.F4
              FROM work_report wr
             WHERE 1 = etc.               )
                SELECT AF1
                           ,AF2
                           ,AF3
                FROM history h
                WHERE something = somethingelse;Is the 'OPEN ,p_result_cur FOR WITH wr AS(' code just a complex cursor for loop? and how does the 'WITH' fit into it?
    Thank you!

    Hi,
    Paul Davis wrote:
    Hi,
    I'm working, in Oracle 10gR2 in Windows XP, on a stored procedure that was given to me mostly completed and I'm trying to decypher the syntax of the cursor.
    CREATE OR REPLACE PROCEDURE p_proc1(p_from_date IN DATE
    ,p_to_date   IN DATE
    ,p_result_cur   IN OUT dbo.pkg_q.ref_cursor) IS
    BEGIN
    OPEN ,p_result_cur FOR WITH wr AS(
    SELECT wr.F1
    ,wr.F2
    ,wr.F3
    ,wr.F4
    FROM work_report wr
    WHERE 1 = etc.               )
    SELECT AF1
    ,AF2
    ,AF3
    FROM history h
    WHERE something = somethingelse;Is the 'OPEN ,p_result_cur FOR WITH wr AS(' code just a complex cursor for loop? and how does the 'WITH' fit into it?I think the comma before p_ref_result_cur is a typo; there should only be space there:
    OPEN p_result_cur FOR WITH wr AS ...There's no loop in the fragment you posted: the OPEN statement does just that; it opens the cursor so later FETCH statements (perhaps inside a loop) can get data.
    "WITH sub_query AS ( .... ) SELECT ..." is one way of writing a query.
    For details, see the SQL Language manual:
    http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_10002.htm#sthref9758

  • Writting exception within cursor for loop

    I have two cursor for loop as
    for rec1 in () loop --loop 1
    for rec2 in () loop --loop2
    <statements>
    end loop;
    end loop
    Now I want to handle exception within my second for loop so that after terminating the loop it will again go to the first loop...
    How to do it ? Please help......

    you may
    BEGIN
       FOR rec1 IN your_select1
       LOOP                                                              --loop 1
          BEGIN
             FOR rec2 IN your_select2
             LOOP                                                         --loop2
                statements;
             END LOOP;
          EXCEPTION
             WHEN OTHERS
             THEN
                log_error;
          END;
       END LOOP;
    END;or ...depending on your exact needs:
    BEGIN
       FOR rec1 IN your_select1
       LOOP                                                              --loop 1
          FOR rec2 IN your_select2
          LOOP
             BEGIN                                                        --loop2
                statements;
             EXCEPTION
                WHEN OTHERS
                THEN
                   log_error;
             END;
          END LOOP;
       END LOOP;
    END;

  • Which is more (faster) performance oriented? Collections or Cursor For Loop

    Hi,
    Please help me regarding a dilemma.
    Is, using a Cursor For Loop faster than a loop run upon a collection variable that was being populated using bulk collect? Why?
    Thanks in advance
    rollerz

    You can just test it by yourself. Can’t you? Ok I was bit curious to know myself so I did this…
    TEST ROUND 1
    SQL> declare
      2     ltime integer;
      3  begin
      4     ltime := dbms_utility.get_time;
      5
      6     for i in (select level from dual connect by level <= 100000)
      7     loop
      8             null;
      9     end loop;
    10
    11     ltime := dbms_utility.get_time - ltime;
    12     dbms_output.put_line('ExecTime:'||ltime/100||' seconds...');
    13  end;
    14  /
    ExecTime:.19 seconds...
    PL/SQL procedure successfully completed.
    SQL> declare
      2     ltime integer;
      3     type my_type is table of integer;
      4     lType my_type;
      5  begin
      6     ltime := dbms_utility.get_time;
      7     select level bulk collect into lType from dual connect by level <= 100000;
      8
      9     for i in 1..lType.count
    10     loop
    11             null;
    12     end loop;
    13
    14     ltime := dbms_utility.get_time - ltime;
    15     dbms_output.put_line('ExecTime:'||ltime/100||' seconds...');
    16  end;
    17  /
    ExecTime:.14 seconds...
    PL/SQL procedure successfully completed.
    TEST ROUND 2
    SQL> declare
      2     ltime integer;
      3  begin
      4     ltime := dbms_utility.get_time;
      5
      6     for i in (select level from dual connect by level <= 100000)
      7     loop
      8             null;
      9     end loop;
    10
    11     ltime := dbms_utility.get_time - ltime;
    12     dbms_output.put_line('ExecTime:'||ltime/100||' seconds...');
    13  end;
    14  /
    ExecTime:.17 seconds...
    PL/SQL procedure successfully completed.
    SQL> declare
      2     ltime integer;
      3     type my_type is table of integer;
      4     lType my_type;
      5  begin
      6     ltime := dbms_utility.get_time;
      7     select level bulk collect into lType from dual connect by level <= 100000;
      8
      9     for i in 1..lType.count
    10     loop
    11             null;
    12     end loop;
    13
    14     ltime := dbms_utility.get_time - ltime;
    15     dbms_output.put_line('ExecTime:'||ltime/100||' seconds...');
    16  end;
    17  /
    ExecTime:.13 seconds...
    TEST ROUND 3
    PL/SQL procedure successfully completed.
    SQL> declare
      2     ltime integer;
      3  begin
      4     ltime := dbms_utility.get_time;
      5
      6     for i in (select level from dual connect by level <= 100000)
      7     loop
      8             null;
      9     end loop;
    10
    11     ltime := dbms_utility.get_time - ltime;
    12     dbms_output.put_line('ExecTime:'||ltime/100||' seconds...');
    13  end;
    14  /
    ExecTime:.16 seconds...
    PL/SQL procedure successfully completed.
    SQL> declare
      2     ltime integer;
      3     type my_type is table of integer;
      4     lType my_type;
      5  begin
      6     ltime := dbms_utility.get_time;
      7     select level bulk collect into lType from dual connect by level <= 100000;
      8
      9     for i in 1..lType.count
    10     loop
    11             null;
    12     end loop;
    13
    14     ltime := dbms_utility.get_time - ltime;
    15     dbms_output.put_line('ExecTime:'||ltime/100||' seconds...');
    16  end;
    17  /
    ExecTime:.13 seconds...
    TEST ROUND 4
    PL/SQL procedure successfully completed.
    SQL> declare
      2     ltime integer;
      3  begin
      4     ltime := dbms_utility.get_time;
      5
      6     for i in (select level from dual connect by level <= 100000)
      7     loop
      8             null;
      9     end loop;
    10
    11     ltime := dbms_utility.get_time - ltime;
    12     dbms_output.put_line('ExecTime:'||ltime/100||' seconds...');
    13  end;
    14  /
    ExecTime:.16 seconds...
    PL/SQL procedure successfully completed.
    SQL> declare
      2     ltime integer;
      3     type my_type is table of integer;
      4     lType my_type;
      5  begin
      6     ltime := dbms_utility.get_time;
      7     select level bulk collect into lType from dual connect by level <= 100000;
      8
      9     for i in 1..lType.count
    10     loop
    11             null;
    12     end loop;
    13
    14     ltime := dbms_utility.get_time - ltime;
    15     dbms_output.put_line('ExecTime:'||ltime/100||' seconds...');
    16  end;
    17  /
    ExecTime:.13 seconds...
    PL/SQL procedure successfully completed.So bulk collect looks faster...
    Thanks,
    Karthick.

  • Cursor For loop question

    Hi,
    I have a cursor in my plsql and I am trying to get the record through a FOR loop. I know that for loop will take care of opening, fetching and closing the cursor implicitly.
    Ex.
    declare
    cursor c1 is
    select * from emp;
    begin
    for l_rec in c1 loop
    end loop;
    My question is i want to check whether the cursor in the for loop is returning any record or not using IF condition.
    where and how i will find that?
    Can anyone help how to do that.
    Rds,
    Nag

    without using boolean variables.Obvious question, WHY?
    If you are so particular..
    SQL> declare
      2   cursor c1 is
      3        select empno, ename, job
      4        from emp
      5        where empno = 7839123;
      6   ex exception;
      7   rec c1%rowtype;
      8  begin
      9   open c1;
    10   fetch c1 into rec;
    11   if c1%notfound then
    12    raise ex;
    13   end if;
    14   loop
    15    dbms_output.put_line(rec.empno||'-->'||rec.ename||'-->'||rec.job);
    16    fetch c1 into rec;
    17    exit when c1%notfound;
    18   end loop;
    19  exception
    20   when ex then
    21    dbms_output.put_line('cur not found');
    22  end;
    23  /
    cur not found
    PL/SQL procedure successfully completed.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Cursor for loop problem

    Hi to all!
    I have this sample data:
    CREATE TABLE person(id NUMBER PRIMARY KEY,
                        first_name VARCHAR2(30),
                        father_id NUMBER REFERENCES person(id),
                        mother_id NUMBER REFERENCES person(id));
    INSERT INTO person
    VALUES (1, 'John', NULL, NULL);
    INSERT INTO person
    VALUES (10, 'John''s son Bill', 1, NULL);
    INSERT INTO person
    VALUES (20, 'John''s daughter Briana', 1, NULL);
    INSERT INTO person
    VALUES (100, 'Bill''s son George', 10, NULL);
    INSERT INTO person
    VALUES (101, 'Bill''s son Matthew', 10, NULL);
    INSERT INTO person
    VALUES (200, 'Briana''s son Greg', 20, NULL);
    INSERT INTO person
    VALUES (201, 'Briana''s son Fred', 20, NULL);
    /Then I execute this PL/SQL anonymous block:
    SET SERVEROUTPUT ON
    DECLARE
        CURSOR children IS
          SELECT s.first_name name
          FROM person s, person p
          WHERE (s.father_id = p.id OR s.mother_id = p.id)
          AND p.id = 1;
        CURSOR g_children IS
            SELECT s.first_name gc_name
            FROM person s, person p
            WHERE (s.father_id = p.id OR s.mother_id = p.id)
            AND p.id IN (SELECT gs.id FROM person gs, person gp
                         WHERE  (gs.father_id = gp.id OR gs.mother_id = gp.id)
                         AND gp.id = 1);      
    BEGIN
        FOR c_rec IN children LOOP
          DBMS_OUTPUT.PUT_LINE(c_rec.name);
             FOR g_rec IN g_children LOOP
                DBMS_OUTPUT.PUT_LINE(g_rec.gc_name);
             END LOOP;
        END LOOP;
    END;I have this result:
    John's son Bill
    Bill's son George
    Bill's son Matthew
    Briana's son Greg
    Briana's son Fred
    John's daughter Briana
    Bill's son George
    Bill's son Matthew
    Briana's son Greg
    Briana's son FredHow could I modify nested for loop, so that I have output like this:
    John's son Bill
    Bill's son George
    Bill's son Matthew
    John's daughter Briana
    Briana's son Greg
    Briana's son FredSo that I have one child and then his children, and then second child and his/her children, and so on.
    Thanks!
    Edited by: Spooky on 2013.02.06 12:54

    Suri wrote:
    BluShadow wrote:
    You would need to parameterize your children query to it only get's the children of that parent.Hi Blu,
    I understood that it can be easily solved by CONNECT BY PRIOR clause.
    Just for curisosity I am asking you, Assume that if we dont know till what level children details exist in person table (for eg: John's son is Bill , Bill's son is XYZ , XYZ son is ABC etc), is there any better way to acheive this using parameter cursor. Oh yeah, sure... use recursion...
    SQL> CREATE TABLE person(id NUMBER PRIMARY KEY,
      2                      first_name VARCHAR2(30),
      3                      father_id NUMBER REFERENCES person(id),
      4                      mother_id NUMBER REFERENCES person(id)
      5                     )
      6  /
    Table created.
    SQL>
    SQL> INSERT INTO person VALUES (1, 'John', NULL, NULL);
    1 row created.
    SQL> INSERT INTO person VALUES (10, 'John''s son Bill', 1, NULL);
    1 row created.
    SQL> INSERT INTO person VALUES (20, 'John''s daughter Briana', 1, NULL);
    1 row created.
    SQL> INSERT INTO person VALUES (100, 'Bill''s son George', 10, NULL);
    1 row created.
    SQL> INSERT INTO person VALUES (101, 'Bill''s son Matthew', 10, NULL);
    1 row created.
    SQL> INSERT INTO person VALUES (200, 'Briana''s son Greg', 20, NULL);
    1 row created.
    SQL> INSERT INTO person VALUES (201, 'Briana''s son Fred', 20, NULL);
    1 row created.
    SQL>
    SQL> set serverout on
    SQL>
    SQL> declare
      2    procedure recurse_persons(father_id in number, lvl number := 0) as
      3      cursor cur_person is
      4        select *
      5        from   person
      6        where  nvl(father_id,0) = nvl(recurse_persons.father_id,0);
      7    begin
      8      for p in cur_person
      9      loop
    10        dbms_output.put_line('['||to_char(lvl+1)||']'||lpad(' ',lvl*2,' ')||p.first_name);
    11        recurse_persons(p.id, lvl+1);
    12      end loop;
    13    end;
    14  begin
    15    recurse_persons(null);
    16  end;
    17  /
    [1]John
    [2]  John's son Bill
    [3]    Bill's son George
    [3]    Bill's son Matthew
    [2]  John's daughter Briana
    [3]    Briana's son Greg
    [3]    Briana's son Fred
    PL/SQL procedure successfully completed.With that, we're just using one cursor definition that suits all, and using recursion to go down each branch of the hierarchy, regardless of how deep. Of course you then run the risk (if it's a very deep hierarchy) of getting a "too many open cursors" error.

Maybe you are looking for

  • Any clue whats going on with time machine?

    Of course I found all kinds of info about not to use seagate for time machine AFTER I bought the NAs110 blackArmor, but since I now own it, I need to try and use it.  Time machine seems to work fine with the device as long as the computer is active.

  • RFKORD10 - FB12 - Customer Account Statement - SmartFORM Driver Program ?

    Hi, Does anybody has smartform driver program for this RFKORD10's SAPScript Driver program? Or anybody done customized code? Please provide the code. Thanks in Advance Vinaa

  • What is the main advantage in EJB Transactions.

    My question is i can have a stateless bean to accept the client requests and will set the Autocommit of database to false and which will invoke the java bean component based up on transaction code and passes the database connection object . the java

  • Connecting Razr Bluetooth to Ford Sync

    Cant get Razr to connect to car which has sync, Ford 2012. It finds it and pin pops up but when I put in pin and click done phone says cannot connect. My Revolution hooked to it with no problem and wife has hers connected.

  • How do I recover a file...

    How do I recover a file in Photoshop Elements 8 after it shuts down unexpectedly?  It is a new file and I didn't get the chance to save it.  Thanks for any help...