PL/SQL block taking different duration

Dear Oracle Gurus
I executed a PL/SQL block which took 10 min to complete. I again executed the same thing , this time it took 8 mins ... after which the time taken was between 7 and 8 min. it was never 10 min .
I was told that this happens due to REDO log that parsing doesnt happens when we execute the process again and hence the time taken is less than the first time .
Kindly clarify me in this regard.
Since i am testing the script i would like to have the correct time taken , whenever i execute it how can we do this .. like clearing the redo log for this particular script
Kindly guide me in this regard
with warm regards
ssr

was told that this happens due to REDO log that parsing doesnt happens when we execute the process again and hence the time taken is less than the first time .
Who mentoned to you that due to REDO Logs , the parsing didnt happen and your block ran more fastly, please for heaven sake ask him/her to read oracle concepts guide.Believe me , he/she really needs it.
Your block's data got cached so you saw a decrease in the time of the query result.This holds true for the block itself but if it was an anonymous block than you wont enjoy the benefit of reusing it actualy.The oracle cache is kicking in here.
Since i am testing the script i would like to have the correct time taken , whenever i execute it how can we do this .. like clearing the redo log for this particular script
I amnot able to get this.What do you mean by correct timing?What exactly is the bench mark that you are trying to meet?
Please redo log clearance has nothing to do with this.
Post the script also what you are trying to run with oracle version of yours.And how you are measuting the time taken?
Aman....

Similar Messages

  • SQL Statement taking different path on 2 servers

    I ran the same SQL statement on two servers (8.1.7.3).
    One is taking the index path and returns results quickly but the second server, which is our production server, is going about a very different path and timing out on the query. I ran the explain plan and see the differences.
    How can I identify the cause to behave differently?
    Can you suggest some ideas and steps that I can further
    investigate?
    Thanks, Moling

    1. The statistics are run nightly on all tables.
    exec sys.dbms_stats.gather_schema_stats ...
    2. What causes BITMAP CONVERSION (TO ROWIDS)and
    BITMAP CONVERSION (From ROWIDS) that I see for table
    U_SUPPLIER_PART_PLANT_MAP? This table has DOMAIN index.
    FAST QUERY
    ==============
    i p PLAN_PLUS_EXP OBJECT_N
    0 SELECT STATEMENT optimizer=FIRST_ROWS (cost=123 card=1 bytes
    =884)
    1 0 NESTED LOOPS (cost=123 card=1 bytes=884)
    2 1 NESTED LOOPS (OUTER) (cost=122 card=1 bytes=877)
    3 2 NESTED LOOPS (OUTER) (cost=121 card=1 bytes=861)
    4 3 NESTED LOOPS (cost=120 card=1 bytes=856)
    5 4 NESTED LOOPS (cost=119 card=2 bytes=1658)
    6 5 NESTED LOOPS (OUTER) (cost=118 card=3 bytes=2472
    7 6 NESTED LOOPS (cost=117 card=3 bytes=2448)
    8 7 NESTED LOOPS (cost=116 card=3 bytes=1506)
    9 8 NESTED LOOPS (OUTER) (cost=115 card=3 byte
    s=1284)
    10 9 NESTED LOOPS (OUTER) (cost=114 card=3 by
    tes=1260)
    11 10 NESTED LOOPS (cost=113 card=3 bytes=12
    39)
    12 11 NESTED LOOPS (OUTER) (cost=112 card=
    3 bytes=1161)
    13 12 NESTED LOOPS (OUTER) (cost=111 car
    d=3 bytes=1137)
    14 13 NESTED LOOPS (OUTER) (cost=110 c
    ard=3 bytes=1113)
    15 14 NESTED LOOPS (cost=109 card=3
    bytes=1089)
    16 15 NESTED LOOPS (cost=101 card=
    87 bytes=30798)
    17 16 TABLE ACCESS (BY INDEX ROW
    ID) of 'U_SUPPLIER_PART_PLANT_MAP' (cost=99 card=87 bytes=30
    363)
    18 17 DOMAIN INDEX of 'CTX_100
    26328' (cost=88)
    19 16 INDEX (UNIQUE SCAN) of 'UK
    USITE1' UNIQUE)
    20 15 TABLE ACCESS (BY INDEX ROWID
    ) of 'U_ORGANIZATION_DIMENSION' (cost=1 card=1 bytes=9)
    21 20 INDEX (UNIQUE SCAN) of 'UK
    UORGANIZATION_DIMENSION' UNIQUE)
    22 14 TABLE ACCESS (BY INDEX ROWID)
    of 'SPM_MATERIAL_GROUP' (cost=1 card=120 bytes=960)
    23 22 INDEX (UNIQUE SCAN) of 'UK_S
    PM_MATERIAL_GROUP' UNIQUE)
    24 13 TABLE ACCESS (BY INDEX ROWID) of
    'U_PURCHASING_GROUP' (cost=1 card=269 bytes=2152)
    25 24 INDEX (UNIQUE SCAN) of 'UK_U_P
    URCHASING_GROUP' UNIQUE)
    26 12 TABLE ACCESS (BY INDEX ROWID) of '
    SPM_UOM' (cost=1 card=428 bytes=3424)
    27 26 INDEX (UNIQUE SCAN) of 'UK_SPM_U
    OM' UNIQUE)
    28 11 TABLE ACCESS (BY INDEX ROWID) of 'SP
    M_SUPP_PART' (cost=1 card=423258 bytes=11004708)
    29 28 INDEX (UNIQUE SCAN) of 'SYS_C00192
    66' UNIQUE)
    30 10 TABLE ACCESS (BY INDEX ROWID) of 'SPM_
    CURRENCY' (cost=1 card=1 bytes=7)
    31 30 INDEX (UNIQUE SCAN) of 'UK_SPM_CURRE
    NCY' UNIQUE)
    32 9 TABLE ACCESS (BY INDEX ROWID) of 'SPM_UO
    M' (cost=1 card=428 bytes=3424)
    33 32 INDEX (UNIQUE SCAN) of 'UK_SPM_UOM' UN
    IQUE)
    34 8 TABLE ACCESS (BY INDEX ROWID) of 'SPM_REFE
    RENCE_ITEM1' (cost=1 card=385224 bytes=28506576)
    35 34 INDEX (UNIQUE SCAN) of 'UK_SPM_REFERENCE
    _ITEM11' UNIQUE)
    36 7 TABLE ACCESS (BY INDEX ROWID) of 'SPD_MANUFA
    CTURER_PART' (cost=1 card=385175 bytes=120944950)
    37 36 INDEX (UNIQUE SCAN) of 'UK_SPD_MANUFACTURE
    R_PART' UNIQUE)
    38 6 TABLE ACCESS (BY INDEX ROWID) of 'SPM_UOM' (co
    st=1 card=428 bytes=3424)
    39 38 INDEX (UNIQUE SCAN) of 'UK_SPM_UOM' UNIQUE)
    40 5 INDEX (UNIQUE SCAN) of 'UK_U_SUPPLIER' UNIQUE)
    41 4 TABLE ACCESS (BY INDEX ROWID) of 'U_SUPPLIER_DIMEN
    SION' (cost=1 card=2 bytes=54)
    42 41 INDEX (UNIQUE SCAN) of 'UK_U_SUPPLIER_DIMENSION'
    UNIQUE)
    43 3 INDEX (UNIQUE SCAN) of 'UK_U_SUPPLIER' UNIQUE)
    44 2 TABLE ACCESS (BY INDEX ROWID) of 'U_SUPPLIER_DIMENSION
    ' (cost=1 card=8276 bytes=132416)
    45 44 INDEX (UNIQUE SCAN) of 'UK_U_SUPPLIER_DIMENSION' UNI
    QUE)
    46 1 TABLE ACCESS (BY INDEX ROWID) of 'S_ROT_CLASS' (cost=1 c
    ard=12943407 bytes=90603849)
    47 46 INDEX (UNIQUE SCAN) of 'UK_S_ROT_CLASS' UNIQUE)
    48 rows selected.
    SLOW QUERY
    ===========
    i p PLAN_PLUS_EXP OBJECT_N
    0 SELECT STATEMENT optimizer=FIRST_ROWS (cost=28278 card=52 by
    tes=49452)
    1 0 NESTED LOOPS (cost=28278 card=52 bytes=49452)
    2 1 NESTED LOOPS (OUTER) (cost=28273 card=52 bytes=48932)
    3 2 NESTED LOOPS (OUTER) (cost=28268 card=52 bytes=48412)
    4 3 NESTED LOOPS (OUTER) (cost=28263 card=52 bytes=47892
    5 4 NESTED LOOPS (cost=28257 card=52 bytes=47372)
    6 5 NESTED LOOPS (cost=28252 card=52 bytes=46800)
    7 6 NESTED LOOPS (cost=28251 card=52 bytes=46488)
    8 7 NESTED LOOPS (OUTER) (cost=305 card=70 bytes
    =37240)
    9 8 NESTED LOOPS (OUTER) (cost=298 card=70 byt
    es=36540)
    10 9 NESTED LOOPS (cost=291 card=70 bytes=359
    10)
    11 10 NESTED LOOPS (cost=285 card=64 bytes=3
    0784)
    12 11 NESTED LOOPS (OUTER) (cost=279 card=
    64 bytes=25792)
    13 12 NESTED LOOPS (OUTER) (cost=272 car
    d=64 bytes=24640)
    14 13 NESTED LOOPS (OUTER) (cost=271 c
    ard=64 bytes=24256)
    15 14 NESTED LOOPS (cost=265 card=64
    bytes=23616)
    16 15 NESTED LOOPS (cost=7 card=2
    bytes=72)
    17 16 TABLE ACCESS (FULL) of 'U_
    SUPPLIER_DIMENSION' (cost=6 card=2 bytes=60)
    18 16 INDEX (UNIQUE SCAN) of 'UK
    USUPPLIER' UNIQUE)
    19 15 TABLE ACCESS (BY INDEX ROWID
    ) of 'SPD_MANUFACTURER_PART' (cost=129 card=375810 bytes=125
    144730)
    20 19 INDEX (RANGE SCAN) of 'NIS
    _P649987' NON-UNIQUE)
    21 14 TABLE ACCESS (BY INDEX ROWID)
    of 'SPM_UOM' (cost=1 card=428 bytes=4280)
    22 21 INDEX (UNIQUE SCAN) of 'UK_S
    PM_UOM' UNIQUE)
    23 13 INDEX (UNIQUE SCAN) of 'UK_U_SUP
    PLIER' UNIQUE)
    24 12 TABLE ACCESS (BY INDEX ROWID) of '
    U_SUPPLIER_DIMENSION' (cost=1 card=8652 bytes=155736)
    25 24 INDEX (UNIQUE SCAN) of 'UK_U_SUP
    PLIER_DIMENSION' UNIQUE)
    26 11 TABLE ACCESS (BY INDEX ROWID) of 'SP
    M_REFERENCE_ITEM1' (cost=1 card=375842 bytes=29315676)
    27 26 INDEX (UNIQUE SCAN) of 'UK_SPM_REF
    ERENCE_ITEM11' UNIQUE)
    28 10 TABLE ACCESS (BY INDEX ROWID) of 'SPM_
    SUPP_PART' (cost=1 card=409148 bytes=13092736)
    29 28 INDEX (RANGE SCAN) of 'NIS_P651218'
    NON-UNIQUE)
    30 9 TABLE ACCESS (BY INDEX ROWID) of 'SPM_CU
    RRENCY' (cost=1 card=1 bytes=9)
    31 30 INDEX (UNIQUE SCAN) of 'UK_SPM_CURRENC
    Y' UNIQUE)
    32 8 TABLE ACCESS (BY INDEX ROWID) of 'SPM_UOM'
    (cost=1 card=428 bytes=4280)
    33 32 INDEX (UNIQUE SCAN) of 'UK_SPM_UOM' UNIQ
    UE)
    34 7 TABLE ACCESS (BY INDEX ROWID) of 'U_SUPPLIER
    PARTPLANT_MAP' (cost=28251 card=304053 bytes=110067186)
    35 34 BITMAP CONVERSION (TO ROWIDS)
    36 35 BITMAP AND
    37 36 BITMAP CONVERSION (FROM ROWIDS)
    38 37 INDEX (RANGE SCAN) of 'NIS_P651535'
    NON-UNIQUE) (cost=765)
    39 36 BITMAP CONVERSION (FROM ROWIDS)
    40 39 SORT (ORDER BY)
    41 40 DOMAIN INDEX of 'CTX_10026328' (co
    st=25098 card=304053)
    42 6 INDEX (UNIQUE SCAN) of 'UK_U_SITE1' UNIQUE)
    43 5 TABLE ACCESS (BY INDEX ROWID) of 'U_ORGANIZATION
    _DIMENSION' (cost=1 card=1 bytes=11)
    44 43 INDEX (UNIQUE SCAN) of 'UK_U_ORGANIZATION_DIME
    NSION' UNIQUE)
    45 4 TABLE ACCESS (BY INDEX ROWID) of 'SPM_MATERIAL_GRO
    UP' (cost=1 card=119 bytes=1190)
    46 45 INDEX (UNIQUE SCAN) of 'UK_SPM_MATERIAL_GROUP' U
    NIQUE)
    47 3 TABLE ACCESS (BY INDEX ROWID) of 'U_PURCHASING_GROUP
    ' (cost=1 card=269 bytes=2690)
    48 47 INDEX (UNIQUE SCAN) of 'UK_U_PURCHASING_GROUP' UNI
    QUE)
    49 2 TABLE ACCESS (BY INDEX ROWID) of 'SPM_UOM' (cost=1 car
    d=428 bytes=4280)
    50 49 INDEX (UNIQUE SCAN) of 'UK_SPM_UOM' UNIQUE)
    51 1 TABLE ACCESS (BY INDEX ROWID) of 'S_ROT_CLASS' (cost=1 c
    ard=13126048 bytes=131260480)
    52 51 INDEX (UNIQUE SCAN) of 'UK_S_ROT_CLASS' UNIQUE)
    53 rows selected.

  • Pl/sql block updating orderId, itemID

    lol here i am again!
    This time its like this:
    i have a table (orderId, itemId, CustomerId, productId, quantity, start_date, end_date, oldRef)
    here are some of the values:
    2477, 1, 201, 111, 1,19-MAR-93,14-APR-93
    2477,2,201,112,1,19-MAR-93,14-APR-93
    2478,1,201,113,1,19-MAR-93,14-APR-93
    2478,2,201,110,19-Mar-93,14-APR-93
    Now as you can see that order_Id is different however order_date and ship_date both match. Now what i want to do is to give them a new orderId, re-arrange itemId if ship_date and order_date match for each customer so the ex above should come out like this:
    1, 1, 201, 111, 1,19-MAR-93,14-APR-93
    1,2,201,112,1,19-MAR-93,14-APR-93
    1,3,201,113,1,19-MAR-93,14-APR-93
    1,4,201,110,19-Mar-93,14-APR-93
    I have created a pl/sql block. It has a cursor that loops around each row of table. Then it stores orderdate, shipdate and customerId. it also has a itemId variable and orderDate variable. OrderDate variable takes its value from orderId sequence and itemId is just a number that increments itself.
    NOW when orderdate,shipdate&customerId are the same, i just update the itemId, if they differ or customer_id changes i get a new order_id, update the variables (orderdate,shipdate,customerid,itemId) but for some reason i dont think it is working!!
    DECLARE
         cursor c1 is
              SELECT
              FROM
                   ph2_item
              order by
                   customer_id,
                   ship_date,
                   order_date
              for update;
         new_order_id     number(8,0) := 0;
         new_item_id     number(4,0) := 1;
         temp_odate      date := '11-JUN-08';
         temp_sdate     date:= '11-JUN-08';
         temp_cId     number(8,0) := 1;
    BEGIN
         FOR rec in c1 LOOP
              IF  rec.customer_id = temp_cId  THEN
                   IF (rec.order_date <> temp_odate OR
                   rec.ship_date <> temp_sdate) THEN
                        new_item_id:= 1;
                                    SELECT  orderid.nextVal into new_order_id from dual;
                        temp_odate :=rec.order_date;
                        temp_sdate :=rec.ship_date;
                   END IF;
              ELSE
                   new_item_id:= 1;
                   SELECT  orderid.nextVal into new_order_id from dual;
                   temp_cid := rec.customer_id;
                   temp_odate :=rec.order_date;
                   temp_sdate :=rec.ship_date;
              END IF;
              update ph2_item
              set order_id = new_order_id, item_id = new_item_id
              where current of c1;
              new_item_id := new_item_id + 1;
         END LOOP;
    END;
    commit;PS> this is not a real life database and just a college assignment!
    just corrected a mistake in one of the example code i posted
    Message was edited by:
    user646562

    well it does seem to give the right results ie. orderId is changed and itemId is rearranged! however the college has an online marker and when i try to submit the code, it says that the max(order_id) of the resulting table (ph2_item) is wrong, the sum(item_id) is wrong and the no of distinct orders is wrong.. this means i am either consolidating orders whne i shouldnt, and this in turns make my item_id wrong..
    also there is one more criteria i should have mentioned but i forgot and that is even if the order_date and ship_date is the same as another order, we will only consolidate them if the customer in question has multiple sites.
    here is the updated pl/sql block taking into account this criteria (using if/else statement)
    DECLARE
         cursor c1 is
              SELECT
              FROM
                   ph2_item
              order by
                   order_date,
                   customer_id
              for update;
         new_order_id     number(8,0) := 0;
         new_item_id     number(4,0) := 1;
         temp_odate date := '11-JUN-08';
         temp_sdate     date:= '11-JUN-08';
         temp_cId     number(8,0) := 1;
         totalSites     number(2,0);
    BEGIN
         FOR rec in c1 LOOP
              select site_count into totalsites from customer_sites where customer_id = rec.customer_id;
              --dbms_output.put_line(rec.customer_id ||' ' || totalsites);
              if totalsites > 1 THEN
                   IF rec.customer_id = temp_cId THEN
                        IF (rec.ship_date <> temp_sdate AND rec.order_date <> temp_odate) AND rec.ship_date is null THEN
                             new_item_id:= 1;
         SELECT orderid.nextVal into new_order_id from dual;
                             temp_odate :=rec.order_date;
                             --temp_sdate :=rec.ship_date;
                        END IF;
                   ELSE
                        new_item_id:= 1;
                        SELECT orderid.nextVal into new_order_id from dual;
                        temp_cid := rec.customer_id;
                        temp_odate :=rec.order_date;
                        --temp_sdate :=rec.ship_date;
                   END IF;     
              ELSE
                   new_item_id:= 1;
                   SELECT orderid.nextVal into new_order_id from dual;
                   temp_cid := rec.customer_id;
                   temp_odate :=rec.order_date;
                   --temp_sdate :=rec.ship_date;
              END IF;      
              update ph2_item
              set order_id = new_order_id, item_id = new_item_id
              where current of c1;
              new_item_id := new_item_id + 1;
         END LOOP;
    END;

  • Insert Stmt behaving differently within a PL/SQL block than independently

    I have an INSERT INTO statement that is behaving different within a PL/SQL block than it does if ran as an independent SQL query. When executed within a PL/SQL block the INSERT statement does insert rows, but only less than 50% of the rows returned by the SELECT statement used by the INSERT. There are no constraints and the only check on the destination table is a NOT NULL for supplier_id column.
    BEGIN
        INSERT INTO suppliers (supplier_id, supplier_name)
        SELECT account_no, name FROM customers WHERE city = 'Newark';
    END;Can anyone help me with this?
    Thanks

    Thought this sounded familiar:
    INSERT INTO statement that is behaving different within a PL/SQL block

  • How to test for différent Select into a single PL/SQL block ?

    Hi,
    I am relatively new to PL/SQL and I am trying to do multiple selects int a single PL/SQL block. I am confronted to the fact that if a single select returns no data, I have to go to the WHEN DATA_NOT_FOUND exception.
    Or, I would like to test for different selects.
    In an authentification script, I am searching in a table for a USER ID (USERID) and an application ID, to check if a user is registered under this USERID for this APPLICATION.
    There are different possibilities : 4 possibilities :
    - USERID Existing or not Existing and
    - Aplication ID found or not found for this particular USERID.
    I would like to test for thes 4 possibilities to get the status of this partiular user regardin this application.
    The problem is that if one select returns no row, I go to the exception data not found.
    In the example below you see that if no row returned, go to the exception
    DECLARE
    P_USERID VARCHAR2(400) DEFAULT NULL;
    P_APPLICATION_ID NUMBER DEFAULT NULL;
    P_REGISTERED VARCHAR2(400) DEFAULT NULL;
    BEGIN
    SELECT DISTINCT(USERID) INTO P_USERID FROM ACL_EMPLOYEES
    WHERE  USERID = :P39_USERID AND APPLICATION_ID = :APP_ID ;
    :P39_TYPE_UTILISATEUR := 'USER_REGISTERED';
    EXCEPTION
    WHEN NO_DATA_FOUND THEN
    :P39_TYPE_UTILISATEUR := 'USER_NOT_FOUND';
    END;I would like to do first this statement :
    SELECT DISTINCT(USERID) INTO P_USERID FROM ACL_EMPLOYEES
    WHERE  USERID = :P39_USERID Then to do this one if the user is found :
    SELECT DISTINCT(USERID) INTO P_USERID FROM ACL_EMPLOYEES
    WHERE  USERID = :P39_USERID AND APPLICATION_ID = :APP_ID ;etc...
    I basically don't want to go to the not found exception before having tested the 4 possibilities.
    Do you have a suggestion ?
    Thank you for your kind help !
    Christian

    Surely there are only 3 conditions to check?
    1. The user exists and has that app
    2. The user exists and doesn't have that app
    3. The user doesn't exist
    You could do this in one sql statement like:
    with mimic_data_table as (select 1 userid, 1 appid from dual union all
                              select 1 userid, 2 appid from dual union all
                              select 2 userid, 1 appid from dual),
    -- end of mimicking your table
             params_table as (select :p_userid userid, :p_appid appid from dual)
    select pt.userid,
           pt.appid,
           decode(min(case when dt.userid = pt.userid and dt.appid = pt.appid then 1
                           when dt.userid = pt.userid then 2
                           else 3
                      end), 1, 'User and app exist',
                            2, 'User exists but not for this app',
                            3, 'User doesn''t exist') user_app_check
    from   mimic_data_table dt,
           params_table pt
    where  pt.userid = dt.userid (+)
    group by pt.userid, pt.appid;
    :p_userid = 1
    :p_appid = 2
        USERID      APPID USER_APP_CHECK                 
             1          2 User and app exist   
    :p_userid = 1
    :p_appid = 3
        USERID      APPID USER_APP_CHECK                 
             1          3 User exists but not for this app
    :p_userid = 3
    :p_appid = 2
        USERID      APPID USER_APP_CHECK                 
             3          2 User doesn't exist  

  • Call to concurrent program in a pl/sql block does not COMMIT data to table

    I have the following PL/SQL block.
                             apps.create_po(x_org_id,x_document_num,x_agent_name,x_vendor_id,x_vendor_site_id,x_ship_to_location,x_bill_to_location,x_creation_date,new_isbn,new_print_key,new_unit_setup_cost,new_unit_run_cost,x_item,x_category_id,x_item_description,x_unit_of_measure,x_quantity,x_unit_price,x_ship_to_org_id,x_promise_date,x_qty_rcv_tolerance, x_deliver_to_location,x_destination_org_id, x_destination_subinventory,x_segment2,x_segment4);
                                  COMMIT;
    FND_GLOBAL.APPS_INITIALIZE(v_user_id,v_resp_id,201);
    v_po_req_id := apps.fnd_request.submit_request('PO','POXPOPDOI',NULL,NULL,NULL,
                                  NULL,'STANDARD',NULL,'Y',NULL,'APPROVED',NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
                                  DBMS_OUTPUT.PUT_LINE('Request ID is:' || v_po_req_id);
                                  IF v_po_req_id <> 0 THEN
                                       dbms_lock.sleep(60);
                                       dbms_output.Put_line('Sleep executed');
                                       COMMIT;
                                       select PHASE_CODE,STATUS_CODE INTO v_phase_code,v_status_code
                                       FROM FND_CONCURRENT_REQUESTS
                                       WHERE REQUEST_ID = v_po_req_id;
                                       dbms_output.put_line('After commit Phase and status codes are = '||v_phase_code || v_status_code);
                                  ELSE
                                       ROLLBACK;
                                  END IF;
                                  dbms_output.put_line('New Po is' || x_document_num);
                                  dbms_output.put_line('Quantity Is'|| x_quantity);
                                  apps.receive_po(x_document_num,x_quantity);
                                  v_rcv_req_id := apps.fnd_request.submit_request('PO','RVCTP',NULL,NULL,NULL,
                                  'BATCH',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,
                                  NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL
                                  DBMS_OUTPUT.PUT_LINE('Request ID is:' || v_rcv_req_id);
                                  IF v_rcv_req_id <> 0 THEN
                                       COMMIT;
                                       DBMS_OUTPUT.PUT_LINE('COMMITED RECEIVING');
                                  ELSE
                                       ROLLBACK;
                                  END IF;
    Presently when this block runs, i can see the new PO number created. Commit is also successfully executed. The last output for the program is
    New Po is 20651
    Quantity Is 450
    But due to some reason, the receiving program(receive_po) cannot retrieve the same PO from the base table.
    But once this pl/sql block is complete, and i call the receving procedure from a different session, the Po is retrieved and receiving against the PO is executed successfully.
    Can someone please suggest a work around ? Is the code missing something ? Since POXPOPDOI is a concurrent program which is executed as an asyncronous process, the commit statement after the call to concurent program does not work but the commit is executed only after it exits the pl/sql block.

    Thanks for responding.
    receive_po() program just inserts the data into RCV_HEADERS_INTERFACE and RCV_TRANSACTIONS_INTERFACE tables based on the PO that is created in the previous step. So basically the new PO created has to be received and the receive_po() just inserts data into the interface tables so that RVCTP can be called after that for receiving.
    Here is the code for the procedure.
    SET SERVEROUTPUT ON;
    --FND_GLOBAL.APPS_INITIALIZE(3,20707,201);
    --Procedure for receiving interface to load data to RCV_HEADERS_INTERFACE and RCV_TRANSACTIONS_INTERFACE
    CREATE OR REPLACE PROCEDURE receive_po (x_ponum IN VARCHAR2,x_quantity IN NUMBER) AS
    v_vendor_site_id NUMBER;
    v_vendor_id NUMBER;
    v_agent_id NUMBER;
    v_ship_to_organization_id NUMBER;
    v_item_id NUMBER;
    v_uom_code varchar2(25);
    v_subinventory varchar2(25);
    v_ship_to_location_id NUMBER;
    BEGIN
    --header information in variables
    dbms_output.put_line('Entering Receiving Insert Procedure');
    dbms_output.put_line('Po number ='||x_ponum||'$');
    dbms_output.put_line('Quantity is ='||x_quantity||'$');
    select pvsa.vendor_site_id into v_vendor_site_id
    FROM po_headers_all pha,po_vendors pv, po_vendor_sites_all pvsa
    where pha.vendor_id = pv.vendor_id
    and pv.vendor_id = pvsa.vendor_id
    and pha.segment1 = x_ponum;
    dbms_output.put_line('Vendor Site ID is' ||v_vendor_site_id);
    select pv.vendor_id into v_vendor_id
    FROM po_headers_all pha,po_vendors pv, po_vendor_sites_all pvsa
    where pha.vendor_id = pv.vendor_id
    and pv.vendor_id = pvsa.vendor_id
    and pha.segment1 = x_ponum;
    dbms_output.put_line('Vendor ID is' ||v_vendor_id);
    select plla.SHIP_TO_ORGANIZATION_ID into v_ship_to_organization_id
    from PO_HEADERS_ALL pha, PO_LINE_LOCATIONS_ALL plla
    where pha.PO_HEADER_ID = plla.PO_HEADER_ID
    and pha.segment1 = x_ponum;
    dbms_output.put_line('Ship to org is' ||v_ship_to_organization_id);
    select agent_id into v_agent_id
    FROM po_headers_all
    WHERE segment1 = x_ponum;
    dbms_output.put_line('Agent ID is' ||v_agent_id);
    --printing header table information
    dbms_output.put_line('vendor id is:'||v_vendor_id);
    dbms_output.put_line('vendor site id is:'||v_vendor_site_id);
    dbms_output.put_line('agent id is:'||v_agent_id);
    dbms_output.put_line('ship to organization id is:'||v_ship_to_organization_id);
    --line information in variables
    --derive item id
    select pla.item_id into v_item_id
    from po_headers_all pha, po_lines_all pla
    where pha.po_header_id = pla.po_header_id
    and pha.org_id = pla.org_id
    and pha.segment1 = x_ponum;
    --derive uom
    select pla.unit_meas_lookup_code into v_uom_code
    from po_headers_all pha, po_lines_all pla
    where pla.po_header_id = pha.po_header_id
    and pla.org_id = pha.org_id
    and pha.segment1 = x_ponum;
    --derive subinventory
    select pda.destination_subinventory into v_subinventory
    from po_headers_all pha, po_lines_all pla,po_distributions_all pda
    where pha.po_header_id = pla.po_header_id
    and pla.po_header_id = pda.po_header_id
    and pla.po_line_id = pda.po_line_id
    and pha.org_id = pla.org_id
    and pla.org_id = pda.org_id
    and pha.segment1 = x_ponum;
    --derive ship to location id
    select ship_to_location_id into v_ship_to_location_id
    from po_headers_all
    where segment1 = x_ponum;
    --printing transaction table details
    dbms_output.put_line('item id is:'||v_item_id);
    dbms_output.put_line('UOM is:'||v_uom_code);
    dbms_output.put_line('subinventory is:'||v_subinventory);
    dbms_output.put_line('ship to location id is:'||v_ship_to_location_id);
    --insert data into the receiving interface header table
    INSERT INTO RCV_HEADERS_INTERFACE
    HEADER_INTERFACE_ID          ,
    GROUP_ID               ,
    PROCESSING_STATUS_CODE      ,
    RECEIPT_SOURCE_CODE          ,
    TRANSACTION_TYPE          ,
    LAST_UPDATE_DATE          ,
    LAST_UPDATED_BY          ,
    LAST_UPDATE_LOGIN,
    CREATION_DATE               ,
    CREATED_BY               ,
    VENDOR_ID               ,
    VENDOR_SITE_ID               ,
    SHIP_TO_ORGANIZATION_ID ,
    EXPECTED_RECEIPT_DATE          ,
    EMPLOYEE_ID               ,
    VALIDATION_FLAG          
    SELECT
    RCV_HEADERS_INTERFACE_S.NEXTVAL,
    RCV_INTERFACE_GROUPS_S.NEXTVAL,
    'PENDING',
    'VENDOR',
    'NEW', -- 'CANCEL',
    sysdate,
    3,
    3,
    sysdate,
    3,
    v_vendor_id,
    v_vendor_site_id,
    v_ship_to_organization_id,
    sysdate+5,
    v_agent_id,
    'Y'
    FROM DUAL;
    commit;
    --insert data into the interface transaction table
    for i in 1..1 loop
    INSERT INTO RCV_TRANSACTIONS_INTERFACE
    (INTERFACE_TRANSACTION_ID     ,
    HEADER_INTERFACE_ID     ,
    GROUP_ID               ,
    LAST_UPDATE_DATE          ,
    LAST_UPDATED_BY          ,
    CREATION_DATE               ,
    CREATED_BY               ,
    LAST_UPDATE_LOGIN,
    TRANSACTION_TYPE          ,
    TRANSACTION_DATE          ,
    PROCESSING_STATUS_CODE      ,
    PROCESSING_MODE_CODE          ,
    TRANSACTION_STATUS_CODE     ,
    QUANTITY               ,
    UNIT_OF_MEASURE          ,
    ITEM_ID ,
    AUTO_TRANSACT_CODE          ,
    RECEIPT_SOURCE_CODE          ,
    SOURCE_DOCUMENT_CODE          ,
    SUBINVENTORY               ,
    DOCUMENT_NUM               ,
    SHIP_TO_LOCATION_ID           ,
    VALIDATION_FLAG
    SELECT
    RCV_TRANSACTIONS_INTERFACE_S.NEXTVAL,
    RCV_HEADERS_INTERFACE_S.CURRVAL,
    RCV_INTERFACE_GROUPS_S.CURRVAL,
    SYSDATE,
    3,
    SYSDATE,
    3,
    3,
    'RECEIVE', --'RECEIVE', -- 'SHIP', --'06-JAN-1998',--question here
    sysdate,
    'PENDING',
    'BATCH',
    'PENDING',
    x_quantity,
    v_uom_code,
    v_item_id,
    'DELIVER', -- 'RECEIVE', --'DELIVER',
    'VENDOR',
    'PO',
    v_subinventory,
    x_ponum,
    v_ship_to_location_id,
    'Y'
    FROM DUAL;
    end loop;
    commit;
    END receive_po;
    I am really stuck and looking out for work arond. Please help.
    Thanks,
    Natasha

  • Can some one please tell me what is the problem in the below pl/sql block

    Hi, I have problem with the following pl/sql block, I need this with bulk operation.
    -- Assume the following scenario, we are validating dept (master) and emp(child) which are my temporary tables and updating the status back to
    -- dept ( for all the validation errors, even if we have any validation at child  it has to update the header record with error message),
    -- upon successful validation insert the data into dept3, and emp3 interms of batches
    -- I have give the sample example with dept and emp, but i have around 10 million records which has around 30-40 validations,
    -- I would like to process them in terms of batches using bulk collection as this would do fast processing
    -- Can some one please tell me how to insert them in terms of bulk with every set of 1000 records in each batch in this example,for every set of 1000 records
    -- i need update batch id with unique number in dept table
    -- with current data i can have 50 batches , I need to pass, deptno as parameter to my emp cursor. 
    -- can some one please tell me how to make this validation and insertion more efficient. so that while inserting the data for every batch it should insert batch id
    -- Tried with LIMIT clause as well but not working
    -- I am correcting the code as per your comments Request you to please suggest me so that I can correct , I am new to PL/sql, started learning now.
    step - 1:
    CREATE TABLE DEPT
           (DEPTNO NUMBER(6) primary key,
            DNAME VARCHAR2(25),
            LOC VARCHAR2(23),
            batch_id number );
    INSERT INTO DEPT VALUES (10, 'ACCOUNTING', 'NEW YORK', null);
    INSERT INTO DEPT VALUES (20, 'RESEARCH',   'DALLAS', null);
    INSERT INTO DEPT VALUES (30, 'SALES',      'CHICAGO', null);
    INSERT INTO DEPT VALUES (40, 'OPERATIONS', 'BOSTON', null);
    step - 2:
    declare
    begin
    for i in 1..50000 loop
    insert into dept values(40+i, 'OPERATIONS'||i,'BOSTON'||i, null);
    end loop;
    commit;
    exception
    when others then
    dbms_output.put_line('Exception occured:'||SQLERRM);
    end;
    step - 3:
    create sequence emp_seq start with 1 increment by 1;
    step - 4:
    CREATE TABLE EMP
           (EMPNO NUMBER(15) NOT NULL primary key,
            ENAME VARCHAR2(20),
            JOB VARCHAR2(20),
            MGR NUMBER(4),
            HIREDATE DATE,
            SAL NUMBER(7, 2),
            COMM NUMBER(7, 2),
            DEPTNO NUMBER(6));
    INSERT INTO EMP VALUES
            (7369, 'SMITH',  'CLERK',     7902,
            TO_DATE('17-DEC-1980', 'DD-MON-YYYY'),  800, NULL, 20);
    INSERT INTO EMP VALUES
            (7499, 'ALLEN',  'SALESMAN',  7698,
            TO_DATE('20-FEB-1981', 'DD-MON-YYYY'), 1600,  300, 30);
    INSERT INTO EMP VALUES
            (7521, 'WARD',   'SALESMAN',  7698,
            TO_DATE('22-FEB-1981', 'DD-MON-YYYY'), 1250,  500, 30);
    INSERT INTO EMP VALUES
            (7566, 'JONES',  'MANAGER',   7839,
            TO_DATE('2-APR-1981', 'DD-MON-YYYY'),  2975, NULL, 20);
    INSERT INTO EMP VALUES
            (7654, 'MARTIN', 'SALESMAN',  7698,
            TO_DATE('28-SEP-1981', 'DD-MON-YYYY'), 1250, 1400, 30);
    INSERT INTO EMP VALUES
            (7698, 'BLAKE',  'MANAGER',   7839,
            TO_DATE('1-MAY-1981', 'DD-MON-YYYY'),  2850, NULL, 30);
    INSERT INTO EMP VALUES
            (7782, 'CLARK',  'MANAGER',   7839,
            TO_DATE('9-JUN-1981', 'DD-MON-YYYY'),  2450, NULL, 10);
    INSERT INTO EMP VALUES
            (7788, 'SCOTT',  'ANALYST',   7566,
            TO_DATE('09-DEC-1982', 'DD-MON-YYYY'), 3000, NULL, 20);
    INSERT INTO EMP VALUES
            (7839, 'KING',   'PRESIDENT', NULL,
            TO_DATE('17-NOV-1981', 'DD-MON-YYYY'), 5000, NULL, 10);
    INSERT INTO EMP VALUES
            (7844, 'TURNER', 'SALESMAN',  7698,
            TO_DATE('8-SEP-1981', 'DD-MON-YYYY'),  1500, NULL, 30);
    INSERT INTO EMP VALUES
            (7876, 'ADAMS',  'CLERK',     7788,
            TO_DATE('12-JAN-1983', 'DD-MON-YYYY'), 1100, NULL, 20);
    INSERT INTO EMP VALUES
            (7900, 'JAMES',  'CLERK',     7698,
            TO_DATE('3-DEC-1981', 'DD-MON-YYYY'),   950, NULL, 30);
    INSERT INTO EMP VALUES
            (7902, 'FORD',   'ANALYST',   7566,
            TO_DATE('3-DEC-1981', 'DD-MON-YYYY'),  3000, NULL, 20);
    INSERT INTO EMP VALUES
            (7934, 'MILLER', 'CLERK',     7782,
            TO_DATE('23-JAN-1982', 'DD-MON-YYYY'), 1300, NULL, 10);
    commit;
    step :- 5
    declare
    cursor c1 is select * from dept;
    k number:=0;
    m number:=0;
    begin
    for i in  c1 loop
    k:=k+1;
    --dbms_output.put_line('k:'||k);
    --dbms_output.put_line('i.deptno:'||i.deptno);
    m:=0;
    for j in 1..5 loop
    m:=m+1;
    --dbms_output.put_line('m:'||m);
    --dbms_output.put_line('i.deptno:'||i.deptno);
    insert into emp values
            (9000+emp_seq.nextval, 'SMITH'||'_'||emp_seq.currval,  'CLERK'||'_'||emp_seq.currval,     7902,
            TO_DATE('17-DEC-1980', 'DD-MON-YYYY'),  800, NULL, i.deptno);
    end loop;
    end loop;
    commit;
    exception
    when others then
    dbms_output.put_line('Exception occured:'||sqlerrm);
    end;
    step :-6
    create table dept3 as select * from dept where 1=2;
    create table emp3 as select * from emp where 1=2;
    alter table dept add object_id number;
    alter table dept add status varchar(20);
    alter table dept add err_msg varchar2(200);
    alter table emp add object_id number;
    -- I have not included the alter statements in the inital creation because i dont want them to insert into dept3 and emp3
    CREATE OR REPLACE
    PACKAGE test_b
    AS
      g_batch_id NUMBER;
      PROCEDURE emp_ins(
          p_EMPNO    NUMBER,
          p_ENAME    VARCHAR2,
          p_JOB      VARCHAR2,
          p_MGR      NUMBER,
          p_HIREDATE DATE,
          p_SAL      NUMBER,
          p_COMM     NUMBER,
          p_DEPTNO   NUMBER);
      PROCEDURE dept_ins(
          p_DEPTNO NUMBER,
          p_dname  VARCHAR2 ,
          p_LOC    VARCHAR2,
          p_batch  NUMBER);
      PROCEDURE validate_prc;
      PROCEDURE main;
    TYPE dept_t
    IS
      TABLE OF dept%ROWTYPE;
      hdr_tbl dept_t;
    TYPE emp_t
    IS
      TABLE OF emp%ROWTYPE;
      line_tbl emp_t;
    TYPE dept_i_t
    IS
      TABLE OF dept3%ROWTYPE;
      hdr_ins_tbl dept_i_t;
    TYPE emp_i_t
    IS
      TABLE OF emp3%ROWTYPE;
      line_ins_tbl emp_i_t;
    END;
    -- pacakge body
    CREATE OR REPLACE
    PACKAGE body test_b
    AS
    PROCEDURE emp_ins(
        p_EMPNO    NUMBER,
        p_ENAME    VARCHAR2,
        p_JOB      VARCHAR2,
        p_MGR      NUMBER,
        p_HIREDATE DATE,
        p_SAL      NUMBER,
        p_COMM     NUMBER,
        p_DEPTNO   NUMBER)
    IS
    BEGIN
      INSERT
      INTO EMP3
          EMPNO ,
          ENAME ,
          JOB ,
          MGR ,
          HIREDATE ,
          SAL ,
          COMM ,
          DEPTNO
        VALUES
          P_EMPNO ,
          P_ENAME ,
          P_JOB ,
          P_MGR ,
          P_HIREDATE ,
          P_SAL ,
          P_COMM ,
          P_DEPTNO
    EXCEPTION
    WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE('EXCEPTION AT EMP INSERT'||SQLERRM);
    END;
    PROCEDURE dept_ins
        p_DEPTNO NUMBER,
        p_dname  VARCHAR2 ,
        p_LOC    VARCHAR2,
        p_batch  NUMBER
    IS
    BEGIN
      INSERT
      INTO DEPT3
          DEPTNO ,
          DNAME ,
          LOC ,
          batch_id
        VALUES
          p_DEPTNO ,
          p_DNAME ,
          p_LOC ,
          p_batch
    EXCEPTION
    WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE('EXCEPTION AT DEPT INSERT'||SQLERRM);
    END ;
    PROCEDURE validate_prc
    IS
      CURSOR c1
      IS
        SELECT * FROM dept WHERE status IS NULL ;--AND rownum <25;
      CURSOR c2(p_dept NUMBER )
      IS
        SELECT * FROM emp WHERE deptno=p_dept;
      e_validation EXCEPTION;
    BEGIN
      OPEN c1;
      LOOP
        FETCH c1 BULK COLLECT INTO hdr_tbl limit 5000;
        SELECT emp_seq.nextval INTO g_batch_id FROM dual;
        EXIT
      WHEN hdr_tbl.count = 0;
        dbms_output.put_line('batch'||g_batch_id);
      END LOOP;
      CLOSE c1;
      dbms_output.put_line('C1 closed');
      --------- Loading data into the inv line table type -------------------------------
      FOR i IN 1 .. hdr_tbl.count
      LOOP
        dbms_output.put_line('started validation');
        -- do header level validations
        IF hdr_tbl(i).dname  IS NULL THEN
          hdr_tbl(i).status  := 'ERROR';
          hdr_tbl(i).err_msg :=',DNAME is null';
        END IF;
        OPEN c2(hdr_tbl(i).deptno);
        LOOP
          FETCH c2 BULK COLLECT INTO line_tbl;
          -- EXIT WHEN c2%NOTFOUND;
        END LOOP;
        CLOSE c2;
        FOR j IN 1 .. line_tbl.count
        LOOP
          -- do line validations
          IF line_tbl(j).ename IS NULL THEN
            hdr_tbl(i).status  := 'ERROR';
            hdr_tbl(i).err_msg :=',ENAME is null';
          END IF;
          BEGIN
            FORALL j IN line_tbl.FIRST .. line_tbl.LAST
            SAVE EXCEPTIONS
            UPDATE EMP
            SET object_id =3
              -- I have multiple columns to update based on validations
            WHERE deptno =hdr_tbl(i).deptno------------
            AND empno    =line_tbl (j).empno;
            COMMIT;
            line_tbl.DELETE;
            dbms_output.put_line( 'Successfully updated emp temp table.');
          EXCEPTION
          WHEN OTHERS THEN
            ROLLBACK;
            dbms_output.put_line( 'Error while updating line temp table. ' || sqlerrm );
            FOR j IN 1 .. sql%BULK_EXCEPTIONS.COUNT
            LOOP
              DBMS_OUTPUT.put_line(' occurred during line temp table updation ' || sql%BULK_EXCEPTIONS(i).ERROR_INDEX );
            END LOOP;
            raise e_validation;
          END;
        END LOOP; -- j
        --CLOSE c2;
        IF hdr_tbl(i).err_msg IS NULL THEN
          hdr_tbl (i).status  := 'VALID';
          hdr_tbl (i).err_msg := NULL;
        END IF;
        -- even if I have line validation failed I have to update header status and erorr msg
        BEGIN
          FORALL i IN hdr_tbl.FIRST .. hdr_tbl.LAST
          SAVE EXCEPTIONS
          UPDATE DEPT
          SET object_id =4,
            status      = hdr_tbl (i).status,
            err_msg     = hdr_tbl (i).err_msg
            --  batch_id =
            -- I have multiple columns to update based on validations
          WHERE deptno = hdr_tbl (i).deptno
          AND status  IS NULL; ------------
          COMMIT;
          hdr_tbl.DELETE;
          dbms_output.put_line( 'Successfully updated dept temp table.');
          --close c1;
        EXCEPTION
        WHEN OTHERS THEN
          ROLLBACK;
          dbms_output.put_line( 'Error while updating hdr temp table. ' || sqlerrm );
          FOR i IN 1 .. sql%BULK_EXCEPTIONS.COUNT
          LOOP
            DBMS_OUTPUT.put_line(' occurred during line temp table updation ' || sql%BULK_EXCEPTIONS(i).ERROR_INDEX );
          END LOOP;
          raise e_validation;
        END;
      END LOOP; --i
    EXCEPTION
    WHEN OTHERS THEN
      DBMS_OUTPUT.PUT_LINE('EXCEPTION AT validate'||SQLERRM);
    END ;
    PROCEDURE main
    IS
      CURSOR dept_ins_cur
      IS
        SELECT * FROM dept WHERE status='VALID';
      CURSOR emp_ins_cur(p_deptno NUMBER)
      IS
        SELECT * FROM emp WHERE deptno= p_deptno;
    BEGIN
      validate_prc;
      OPEN dept_ins_cur;
      LOOP
      FETCH dept_ins_cur BULK COLLECT INTO hdr_ins_tbl limit 1000
      EXIT
      WHEN dept_ins_cur%NOTFOUND;
      END LOOP;
      CLOSE dept_ins_cur;
      --------- Loading data into the inv line table type -------------------------------
      FOR i IN 1 .. hdr_tbl.count
      loop
      dept_ins(hdr_ins_tbl(i).deptno ,
      hdr_ins_tbl(i).DNAME ,
      hdr_ins_tbl(i).LOC , emp_seq.nextval);
      commit;
      OPEN emp_ins_cur(hdr_ins_tbl(i).deptno);
      LOOP
      FETCH emp_ins_cur BULK COLLECT INTO line_ins_tbl;
      --EXIT WHEN emp_ins_cur%NOTFOUND;
      END LOOP;
      CLOSE emp_ins_cur;
      for j in 1..line_ins_tbl.count loop
      emp_ins(line_ins_tbl(j).EMPNO ,
      line_ins_tbl(j).ENAME ,
      line_ins_tbl(j).JOB ,
      line_ins_tbl(j).MGR ,
      line_ins_tbl(j).HIREDATE ,
      line_ins_tbl(j).SAL ,
      line_ins_tbl(j).comm ,
      line_ins_tbl(j).DEPTNO );
      end loop;
      end loop;
      commit;
      BEGIN
      forall i IN hdr_ins_tbl.first .. hdr_ins_tbl.last
      SAVE exceptions
      UPDATE dept
      SET status   = 'INSERTED',
      err_msg  = null
      WHERE deptno=hdr_ins_tbl (i).deptno
      AND status   = 'VALID';
      COMMIT;
      hdr_ins_tbl.delete;
      dbms_output.put_line( 'inserting into temp tables.');
      EXCEPTION
      WHEN OTHERS THEN
      rollback;
      end;
    EXCEPTION
    WHEN OTHERS THEN
      dbms_output.put_line('exception in main' ||SQLERRM);
    END ;
    END;
    Thanks in advance...
    Message was edited by: 888025

    Hi, I have problem with the following pl/sql block
    Well, as Hoek already said, that is the understatement of the century.
    I can't be absolutely certain but I think that set of DDL and code that you posted has just about every possible error and design issue that there is! It would make an excellent addition to BluShadow's FAQs an an example of what NOT to do.
    I don't think it is even possible to 'fix the basics first' as Hoek suggested. IMHO the first step needs to be to create a functional requirements document (FRD) that explains in detail WHAT needs to be done. That doc should also contain info about how any errors/recovery/restart is to be handled. It is premature to try to implement ANY solution without first knowing what is needed functionally.
    Once the FRD is done you should do a walk-through based on your current architecture and sample data to make sure that the document really covers ALL of the steps that need to be performed and that it adequately explains how to deal with any processing or data issues that might arise.
    The next document you need is the TRD - Technical Requirements Doc that covers the different technical implementions of the FRD that can be done and the advantages/disadvantages of each.
    Then you can start working on a prototype.
    1. The DDL you posted isn't coherent - there are CREATE table statements and then later ALTER statements that add additional columns. There doesn't appear to be any reason for not including ALL of the columns in the CREATE table statement.
    2. You are using PL/SQL types instead of SQL types. That makes it impossible to use those types in SQL statements and makes it much more difficult to test since it is much easier to test a query in SQL (e.g. using sql*plus) that to embed the query in PL/SQL.
    3. You are defining the same type twice but giving it different names.
    TYPE dept_t
       IS
          TABLE OF dept%ROWTYPE
             INDEX BY binary_integer;
    TYPE dept_i_t
       IS
          TABLE OF dept%ROWTYPE
             INDEX BY binary_integer;
    Those are both based on the same DEPT table! Why the duplication?
    Also you are using associative arrays instead of just using nested tables. Get rid of the INDEX BY clause.
    4. You have some serious architectural and data model issues
    -- Assume the following scenario, we are validating dept (master) and emp(child) which are my temporary tables and updating the status back to
    -- dept ( for all the validation errors, even if we have any validation at child  it has to update the header record with error message),
    Why would you do that? You say 'it has to update the header record ...'. Says who? That is just one indication that you are trying to implement a 'solution' before you have adequately defined the 'problem'.
    Typically you would NOT alter any of the data tables; any validation errors/issues would get inserted into a table specifically designed to hold/log those issues. That table would contain key field values to correlate with the source of the error.
    Those 'master' and 'child' entities are two SEPARATE things. Issues with a 'master' row have NOTHING to do with any possible child rows.
    And issues with a 'child' row have NOTHING to do with any possible master rows. The ONLY connection between 'child' and 'master' is the foreign key that correlates them.
    So you don't necessarily have to validate the 'child' rows in sync with their 'master' row. In many cases you would have a procedure that performs validation of the entire set of 'master' rows and log those issues/problems. You would use a different procedure to validate the entire set of 'child' rows and log their issues.
    Those validation procedures can often work with ALL of the data using SQL statements instead of bulk processing.
    5. You are using loop constructs that are not valid for the type of processing you are using
    LOOP
        FETCH c1 BULK COLLECT INTO hdr_tbl;
        EXIT
      WHEN c1%NOTFOUND;
      END LOOP;
    There can be NO exit since the bulk collect with either get EVERYTHING or NOTHING. Possibly that is just a holdover from your attempt to use the LIMIT clause but you removed that clause from the FETCH; I don't know.
    There is so much wrong with what you posted it is really rather pointless to try to 'fix' it.
    I suggest you start over and clarify and DOCUMENT the actual requirements without prejudice about the solution that someone seems to want to force on you.

  • Alter table then Update in PL/SQL block

    I am trying to alter the table then update it :
    declare
    colCount number;*
    begin*
    select count(*) into colCount from all_tab_cols where table_name = 'TEST' and owner = 'TEST_OWNER';*
    dbms_output.put_line('No of Columns in the table : ' || colCount);*
    if colCount = 2  then*
    dbms_output.put_line('Table needs upgrade');*
    execute immediate('ALTER TABLE TEST ADD COL1 VARCHAR2(100) NULL');*
    UPDATE TEST SET COL1 = '123';*
    commit;*
    else*
    dbms_output.put_line('No Changes Required');*
    end if;*
    end;*
    Oracle complains that "COL1" is an invalid identifier.
    I also tried substitute the UPDATE statement with
    **     execute immediate('UPDATE TEST SET VCHCHARSET_OUT='UTF8' WHERE VCHCHARSETNAME='UTF8'');**
    and there is something wrong with the construction of an Update statement in the parenthesis.
    Am I taking the right approach and just need to figuire out the syntax of single quotes or something else is wrong?
    thanks in advance.

    Yes, you are absolutely right, I shouldn't alter the table and then update the values.
    The reason I need to do it relates to the migration process we utilize in our company. Initially I had a set of SQL commands which I executed migrating from one environment to another and eventually to Production. I had an error in the last SQL command which caused migration process to produce "Failure", however the table was already altered and all the rows except the last one were updated. Since I can't successfully migrate to Production with the failed process I have to generate a PL/SQL block which will take in consideration that in one environment the table has already been modified and in the other one is still needs to be changed.

  • Copy Command in Pl/Sql block

    Can I use Copy command in Pl/Sql.For example :-
    Declare
    cursor c1 is select table_name from all_tables
    where owner = 'LSP' and rownum = 1;
    v1 varchar2(2000);
    Begin
    for c2 in c1 loop
    v1:='copy from lsp/lsp123479@dvlaq to scott/[email protected] create '|| c2.table_name ||' using select * from '||c2.table_name;
    execute immediate v1;
    end loop;
    end;
    Its not running properly giving an error as invalid Sql statement .
    Is it bcoz Copy command cannot be used in a Pl/Sql Block.

    Is there any other way to move the Table & data to another Data Base .Database link is the obvious one. And the SQL statement would look something like this (on the target database):
    SQL> create table FOO nologging as select * from FOO@sourcedb;
    However, the first question I always ask if why? What one may think is the solution to a problem is not always the best solution. So one need to identify the problem first, and then see what solutions there are and which one is the best fit.
    Other options are replication (using materialised views for example), Data Pump (available with 10G) - even could be Data Guard, a standby database, or a Real Application Cluster... depending on just what the problem and actual requirements are.
    Also important to note that SQL*Plus has its own set of commands. Do not confuse these commands (like EXEC, COPY, CONNECT, HOST etc) with the SQL and PL/SQL Languages. Not only are they executed by different software products, SQL*Plus commands are executed on the client and SQL (and PL/SQL) runs inside the Oracle database instance.

  • Error in PL/SQL Block of Trigger

    Hi all,
    I have written a trigger whose PL/SQL block contains a simple select statment among many other statements.
    Now I find that, if the select statement returns no rows the trigger does not continue its operation further and aborts there itself. And if the select statement returns some rows, then it works fine.
    I tried to execute a simplified PL/SQL block of the trigger in SQL*Plus and following were the results:
    declare
    tempdate date;
    begin
    select trdt into tempdate from inv_trans;
    if sql%notfound then
    null;
    end if;
    end;
    When no data is present in inv_trans table, the result was:
    declare
    ERROR at line 1:
    ORA-01403: no data found
    ORA-06512: at line 4
    And when the table inv_trans had data, the result was:
    PL/SQL procedure successfully completed.
    Why is the piece of code flashing an error when I have already given a treatment if no data is found.
    Why is it taking "No Data in table" as an abnormal condition and not normal?
    THanks in advance
    Warm Regards
    Manu

    In your case you have to use a cursor:
    declare
      cursor c_cur is
        select trdt from inv_trans;
      r_cur   c_cur%rowtype;
    begin
      open c_cur;
      fetch c_cur into r_cur;
      if c_cur%notfound then
    [pre]                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • First execution of pl/sql block is slow.

    Hi,
    I've introduced TimesTen to improve performance of a pl/sql block in Oracle.
    For that I created certain cachegroups in TimesTen to cache the oracle data.
    After everything is done on TimesTen, when we run the pl/sql block on TimesTen, I observed that it is taking 35 Seconds ( against 48 secs on Oracle) for first time execution on Timesten.  Subsequent execution of same pl/sql block with same parameters are taking just 6 seconds. I want to achieve the same throughput ( 6 sec) when the pl/sql block is executed for the first time. Can you please suggest what exactly I should look into.
    Thanks
    Amit

    Thanks you so much Chris for your response.
    Please find the requested info here:
    1=>
    C:\TimesTen\tt1122_64\bin>ttversion
    TimesTen Release 11.2.2.5.0 (64 bit NT) (tt1122_64:53396) 2013-05-23T16:26:12Z
      Instance admin: shuklaam
      Instance home directory: C:\TimesTen\TT1122~1\
      Group owner: ES\Domain Users
      Daemon home directory: C:\TimesTen\TT1122~1\srv\info
      PL/SQL enabled.
    2, 3=>Complete DSN definition and CG definitions is available in the  doc here https://docs.google.com/file/d/0BxQyEfoOqCkDWVZmSG90NUd5bGM/edit?usp=sharing
    4=>I can't share the source code due to my company policies, but I'm explaining here what exactly it is doing.
    1. Based on the parameters to the proc, build a cursor, and fetch records from various tables.
    2. insert them into pl/sql tables.
    3. Do some calculations on those records, & calculate certain amounts.
    4. Insert these values into a temporary table, and display to the UI.
    At the same time, I found a metalink note 1272819.1 which stats this is a known phenomena. Not sure if setting DSN attribute MemoryLock=4 will resolve the issue.
    Also, I couldn't find this attribute in windows DSN definition any where. Can you please point me where exactly I need to set it.
    Thanks
    Amit

  • Stored Procedure Vs PL-SQL Block

    Hi,
    I came across an interesting problem last week. Fortunately, I was able to solve it or find an acceptable workaround for myself. But wanted to get some clarification from the experts. So posting it here.
    Also, I am new to Orcle, so please excuse any shortcomings in the post.
    My data model has following tables-
    TABLE_PARENT (ID, other columns)
    TABLE_CHILD (ID, other columns, PARENT_ID_FK)
    Here, ID is the primary key column for the respective tables; PARENT_ID_FK is the foreign key referencing the ID column from the TABLE_PARENT.
    I created a stored procedure programmatically (using MS Excel) to insert records in the two tables. The stored procedure has insert statements for an indefinite number of records in the parent table and for every such record, there's a corresponding record inserted in the child table. Here's the sample code.
    BEGIN
    /*first record*/
    parent_id := MY_SEQUENCE_GENERATOR.NEXTVAL;
    INSERT INTO TABLE_PARENT(ID, other columns) VALUES (parent_id, other values);
    INSERT INTO TABLE_CHILD(ID, other values,parent_id );
    /*second record*/
    parent_id := MY_SEQUENCE_GENERATOR.NEXTVAL;
    INSERT INTO TABLE_PARENT(ID, other columns) VALUES (parent_id, other values);
    INSERT INTO TABLE_CHILD(ID, other values,parent_id );
    /*third record*/
    parent_id := MY_SEQUENCE_GENERATOR.NEXTVAL;
    INSERT INTO TABLE_PARENT(ID, other columns) VALUES (parent_id, other values);
    INSERT INTO TABLE_CHILD(ID, other values,parent_id );
    /*and so on*/
    END
    When I run this stored procedure, I keep getting following exception intermittently-
    ORA-02291: integrity constraint violated-parent key not found tips.
    My thinking is that it comes because the insert statements are executing ahead of turn of the parent_id assignment statement. And this is happening possibly because of some parallelism that is taking place during the execution of the stored procedure, or, some sort of optmization that the DB server does (though erroneously) when it compiles the stored procedure.
    I tried out everything that I could think of but it didn't go away. Finally, when I executed the same set of statements as a PL-SQL block, it worked fine.
    To understand it better, I am looking for clarification on the following questions.
    1) Why does the exception come with stored procedure but not with PL-SQL block? Is my reasoning given above correct (parallelism or some sort of optimization coming into play)?
    2) If it is due to parallelism, how to run a Oracle stored procedure with defree of prallelism set to 1?
    3) If it is due to optimization done by the compiler, how to instruct the compiler to not do any such optimization. Also, in any case, isn't it an error to optimize but lose program semantics?
    4) Another question related to the same piece of work I have is to use transactions in the PL-SQL block, I had to explicitly COMMIT/ROLLBACK it in the code. In whatever references I had read, it was said that by default the transaction begins with BEGIN statement and commits with END. Also, it seems to work with a Stored Proedure though. So is it that a PL_SQL block needs explicity call to COMMIT/ROLLBACK to achive transactions but stored procedures do not?
    Any inputs/clarifications will be much appreciated.
    Thank you
    Neelesh

    Ok, your last couple of paragraphs were helpful. Here're the details that were missing in my earlier post.
    - I am on Oracle 10.2.0.
    - Table definitions-
    CREATE TABLE "MYUSER"."TABLE_PARENT"
    *(     "ID" NUMBER(19,0) NOT NULL ENABLE,*
    *     "NAME" VARCHAR2(30),*
    *     "DESCRIPTION" VARCHAR2(80),*
    *     "RULETYPE" NUMBER(10,0) NOT NULL ENABLE,*
    *     "OPERATOR" NUMBER(10,0),*
    *     "MININTERCEPT" FLOAT(126),*
    *     "PRIORITY" NUMBER(10,0),*
    *     "PENALTY" NUMBER(10,0),*
    *     "STATUS" NUMBER(10,0),*
    *     PRIMARY KEY ("ID")*
    USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
    STORAGE(INITIAL 131072 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
    PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
    TABLESPACE "USERS"  ENABLE,
    *) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING*
    STORAGE(INITIAL 131072 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
    PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
    TABLESPACE "USERS"
    CREATE TABLE "MYUSER"."TABLE_CHILD"
    *(     "ID" NUMBER(19,0) NOT NULL ENABLE,*
    *     "WEIGHT" NUMBER(19,0),*
    *     "PARENTID_FK" NUMBER(19,0),*
    *     PRIMARY KEY ("ID")*
    USING INDEX PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS
    STORAGE(INITIAL 131072 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
    PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
    TABLESPACE "USERS"  ENABLE,
    *     CONSTRAINT "FK3A78BF1E6A9DCE51" FOREIGN KEY ("PARENTID_FK")*
    *     REFERENCES "MYUSER"."TABLE_PARENT" ("ID") ENABLE*
    *) PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 NOCOMPRESS LOGGING*
    STORAGE(INITIAL 131072 NEXT 1048576 MINEXTENTS 1 MAXEXTENTS 2147483645
    PCTINCREASE 0 FREELISTS 1 FREELIST GROUPS 1 BUFFER_POOL DEFAULT)
    TABLESPACE "USERS"
    - The Stored procedure definition is-
    CREATE OR REPLACE PROCEDURE LOAD_RULES_SP AS
    ruleid NUMBER(19,0);
    tempid NUMBER(19,0);
    BEGIN
    */* First parent record */*
    SELECT IDGENERATOR.NEXTVAL INTO ruleid FROM dual;
    INSERT INTO TABLE_PARENT (ID, NAME, DESCRIPTION, RULETYPE, OPERATOR, MININTERCEPT, PRIORITY, penalty, STATUS) VALUES (ruleid, 'Rule 1',null,3,0,0,null,null,1);
    */* Corresponding child records */*
    SELECT IDGENERATOR.NEXTVAL INTO tempid FROM dual;
    INSERT INTO TABLE_CHILD (id, weight, PARENTID_FK)
    VALUES (tempid, 0.2, ruleid);
    SELECT IDGENERATOR.NEXTVAL INTO tempid FROM dual;
    INSERT INTO TABLE_CHILD (id, weight, PARENTID_FK)
    VALUES (tempid, 0.5, ruleid);
    SELECT IDGENERATOR.NEXTVAL INTO tempid FROM dual;
    INSERT INTO TABLE_CHILD (id, weight, PARENTID_FK)
    VALUES (tempid, 0.3, ruleid);
    */* First parent record */*
    SELECT IDGENERATOR.NEXTVAL INTO ruleid FROM dual;
    INSERT INTO TABLE_PARENT (ID, NAME, DESCRIPTION, RULETYPE, OPERATOR, MININTERCEPT, PRIORITY, penalty, STATUS) VALUES (ruleid, 'Rule 1',null,3,0,0,null,null,1);
    */* Corresponding child records */*
    SELECT IDGENERATOR.NEXTVAL INTO tempid FROM dual;
    INSERT INTO TABLE_CHILD (id, weight, PARENTID_FK)
    VALUES (tempid, 0.2, ruleid);
    SELECT IDGENERATOR.NEXTVAL INTO tempid FROM dual;
    INSERT INTO TABLE_CHILD (id, weight, PARENTID_FK)
    VALUES (tempid, 0.5, ruleid);
    SELECT IDGENERATOR.NEXTVAL INTO tempid FROM dual;
    INSERT INTO TABLE_CHILD (id, weight, PARENTID_FK)
    VALUES (tempid, 0.3, ruleid);
    */* And so on for a few parent records more */*
    END;
    Can you throw some light on the exception I was seeing now? Note that when I changed from stored procedure to an anonymous block, it worked fine.
    One correction in my earlier post is that as the code snippet shows, there are multiple inserts in the child table for every record inserted in the parent one.

  • PERFORMANCE BAD WHEN CURSORS ARE USED WITHIN PL/SQL BLOCKS

    There are poor database performance at Oracle 10g
    For some cursor selects, the performance is under Oracle 10g
    significant slower than under Oracle 9i.On a test system (Oracle 9) the
    problem does not reproduce, on the 10g system however always.
    The simple execution of the base select statement was on both
    databases in roughly of the same speed. If however a cursor was defined and
    those executed within a PL/SQL block (without involving the user interface),
    then the time behavior was in accordance with the observed behavior
    behavior on the user interface.
    By adding of the hint first_rows on both machines a
    similar (fast) time behavior can be achieved.
    Conclusion: Something in the (Optimizer) settings of the Oracle-10
    databases must be fundamentally different than that of Oracle 9. Or Oracle
    10 has a real problem. The analysis and solution of this general
    problem seems to me more reasonable than the solution of individual performance
    problems.
    can you help me, many thanks

    Hello, thanks for the explanatory notes.
    Here are the concerned Script. The only difference is the Hint (with Hint = good püerformance; without Hint = bad performance)
    DECLARE
    b BOOLEAN;
    BEGIN
    b := plogin.batch_login('**', '****', 717, FALSE);
    prost.reload_context;
    END;
    DECLARE
    l_ma_kuerzel VARCHAR2(100) DEFAULT NULL;
    l_sta_id mitarbeiter_historie.sta_id%TYPE;
    l_org_id organisationseinheit.org_id%TYPE;
    l_pv_like mitarbeiter.ma_name%TYPE;
    l_typ_id typ.typ_id%TYPE;
    l_mihi_beginn VARCHAR2(40);
    l_ma_ausgeschieden VARCHAR2(40);
    l_ma_ldap mitarbeiter.ma_ldap%TYPE;
    l_smodify_form VARCHAR2(80);
    l_sform_typ VARCHAR2(80);
    l_sheader VARCHAR2(200);
    l_nurlsource NUMBER;
    l_nurldestination prosturl.pur_id%type;
    l_ma_like VARCHAR2(100) DEFAULT NULL;
    l_nma_typ NUMBER;
    l_bshow BOOLEAN;
    l_counter NUMBER DEFAULT 0;
    cursor ma_list_not_all_detail(
    p_ma_like IN VARCHAR2 DEFAULT NULL,
    p_ma_kuerzel IN VARCHAR2 DEFAULT NULL,
    p_sta_id IN VARCHAR2 DEFAULT NULL,
    p_org_id IN VARCHAR2 DEFAULT NULL,
    p_typ_id IN VARCHAR2 DEFAULT NULL,
    p_mihi_beginn IN VARCHAR2 DEFAULT NULL,
    p_pv_like IN VARCHAR2 DEFAULT NULL,
    p_ma_ausgeschieden IN VARCHAR2 DEFAULT NULL,
    p_ma_ldap IN VARCHAR2 DEFAULT NULL
    ) IS
    SELECT /*+ first_rows */
    ma.ma_id ma_id
    , view_fkt.display_ma(mihi.typ_id_mt
    , view_fkt.cat_maname(ma.ma_name
    , ma.ma_zusatz
    , ma.ma_titel
    , ma.ma_vorname)) name
    , view_fkt.display_ma(mihi.typ_id_mt,ma.ma_kuerzel) ma_kuerzel
    , typ.typ_value mt_kuerzel
    , substr(org.typ_id,4,length(org.typ_id)) || ' ' || org.org_name||' ('||org.org_ktr||')' org_name
    , to_char(mihi.mihi_beginn, 'dd.mm.yyyy') beginn
    , decode(pv.ma_name ||' '|| pv.ma_titel ||' '|| pv.ma_vorname
    , ' ',prost_cons.t_blank
    , pv.ma_name||', '||pv.ma_titel||' '||pv.ma_vorname) pv_kuerzel
    , mihi.sta_id sta_id
    , nvl(to_char(ma.ma_ausgeschieden,'dd.mm.yyyy'), ' ') ausgeschieden
    , nvl(to_char(mihi.mihi_wochenarbeitszeit,'90D00'),' ') wochenarbeitszeit
    , nvl(to_char(mihi.mihi_taz_mo,'90D00'),' ') taz_mo
    , nvl(to_char(mihi.mihi_taz_di,'90D00'),' ') taz_di
    , nvl(to_char(mihi.mihi_taz_mi,'90D00'),' ') taz_mi
    , nvl(to_char(mihi.mihi_taz_do,'90D00'),' ') taz_do
    , nvl(to_char(mihi.mihi_taz_fr,'90D00'),' ') taz_fr
    , nvl(to_char(mihi.mihi_taz_sa,'90D00'),' ') taz_sa
    , nvl(to_char(mihi.mihi_taz_so,'90D00'),' ') taz_so
    , nvl(ma.ma_ldap, ' ') ma_ldap
    , mihi.mihi_beginn mihi_beginn
    , mihi.mihi_order_no mihi_order_no
    , mihi.mihi_order_pos mihi_order_pos
    FROM organisationseinheit org
    , typ typ
    , mitarbeiter pv
    , mitarbeiter ma
    , v$mihi_id mid
    , mitarbeiter_historie mihi
    , v$access_orgs_th_t th
    WHERE mihi.org_id = th.org_id
    AND mid.mihi_id = mihi.mihi_id
    AND ma.ma_id = mid.ma_id
    AND ma.ma_delete = 'n'
    AND ma.ma_virtualitaet = 'N'
    AND (p_ma_like IS NULL
    OR ma.ma_name LIKE p_ma_like)
    AND (p_ma_kuerzel IS NULL
    OR ma.ma_kuerzel LIKE p_ma_kuerzel)
    AND (p_sta_id IS NULL
    OR mihi.sta_id = p_sta_id)
    AND (p_org_id IS NULL
    OR org.org_id = p_org_id)
    AND (p_typ_id IS NULL
    OR typ.typ_id = p_typ_id)
    AND mihi_beginn >= nvl(p_mihi_beginn,to_date('01.01.1960','dd.mm.yyyy'))
    AND (p_pv_like IS NULL
    OR pv.ma_name LIKE p_pv_like)
    AND (ma.ma_ausgeschieden >= nvl(p_ma_ausgeschieden,to_date('01.01.1960','dd.mm.yyyy'))
    AND ma.ma_ausgeschieden - 1 < nvl(p_ma_ausgeschieden,to_date('01.01.1960','dd.mm.yyyy'))
    OR p_ma_ausgeschieden IS NULL)
    AND (p_ma_ldap IS NULL
    OR ma.ma_ldap LIKE p_ma_ldap)
    AND pv.ma_id (+)= mihi.ma_id_pv
    AND org.org_id (+)= mihi.org_id
    AND typ.typ_id = mihi.typ_id_mt
    ORDER BY upper(ma.ma_name), upper(ma.ma_vorname);
    l_result ma_list_not_all_detail%ROWTYPE;
    BEGIN
    l_nMA_Typ := pmitarbeiter.cn_Incomplete_Ma;
    l_ma_like := NULL;
    l_ma_kuerzel := NULL;
    l_sta_id := NULL;
    l_org_id := 'KST0000421301';
    l_typ_id := NULL;
    l_mihi_beginn := NULL;
    l_pv_like := NULL;
    l_ma_ausgeschieden := NULL;
    l_ma_ldap := NULL;
    IF (l_ma_like IS NOT NULL
    OR l_ma_kuerzel IS NOT NULL
    OR l_sta_id IS NOT NULL
    OR l_org_id IS NOT NULL
    OR l_typ_id IS NOT NULL
    OR l_mihi_beginn IS NOT NULL
    OR l_pv_like IS NOT NULL
    OR l_ma_ausgeschieden IS NOT NULL
    OR l_ma_ldap IS NOT NULL) THEN
    -- fuer Mitarbeiter unvollstandig wird ein andere cursor angesprochen
    -- um der Mitarbeiter vollstandig zu kriegen soll ein Standort,
    -- Arbeitszeitmodel, Bereich und Tagesarbeitszeiten ausgevult wirden
    -- Wenn er dan gespeichert wirdt wirden die betriffende velder gespeichert
    -- und wirdt das Feld Virtualiteat auf R gesetzt (war N)
    l_counter := 0;
    dbms_output.put_line(to_char(sysdate, 'sssss'));
    FOR j IN ma_List_Not_All_Detail(
    l_ma_like,
    l_ma_kuerzel,
    l_sta_id,
    l_org_id,
    l_typ_id,
    l_mihi_beginn,
    l_pv_like,
    l_ma_ausgeschieden,
    l_ma_ldap
    ) LOOP
    l_counter := l_counter + 1;
    dbms_output.put_line(l_counter);
    dbms_output.put_line(j.ma_kuerzel);
    END LOOP;
    dbms_output.put_line(to_char(sysdate, 'sssss'));
    END IF;
    return;
    EXCEPTION
    WHEN OTHERS THEN
    dbms_output.put_line(sqlerrm);
    END;
    =============
    Thank you

  • TREAT into an SQL request VS into pl/sql block

    Hello,
    Something escape my understanding. The question is a little bit long for a probably short answer.
    Thanks bothering reading it.
    Claude
    Situation:
    CREATE OR REPLACE TYPE "A" AS OBJECT (v_a NUMBER) NOT FINAL;
    CREATE OR REPLACE TYPE "B" UNDER A (v_b NUMBER)
    ALTER TYPE B ADD MEMBER FUNCTION f_60 RETURN VARCHAR2 CASCADE;
    CREATE OR REPLACE TYPE BODY "B" AS
    MEMBER FUNCTION f_60 RETURN VARCHAR2 IS
    BEGIN
    RETURN 'FROM F_60';
    END f_60;
    END;
    CREATE TABLE "TA" OF "A";
    I INSERT successfully 3 instances of A and 2 instances of B INTO TA.
    After I launch this working fine: SELECT TREAT( VALUE(p) AS B).f_60() FROM TA p;
    Result-->
    TREAT(VALUE(P)ASB).F_60()
    FROM F_60
    FROM F_60
    <---
    ...But after that I try the following PL/SQL block:
    DECLARE
    TYPE list_A IS TABLE OF A;
    v_list list_A;
    BEGIN
    SELECT VALUE(p) BULK COLLECT INTO v_list
    FROM TA p; -- (ok if uncommented ->) WHERE VALUE(p) IS OF (B);
    FOR r IN v_list.FIRST .. v_list.LAST LOOP
    DBMS_OUTPUT.PUT_LINE(TREAT( v_list(r) AS B).f_60 );
    END LOOP;
    END;
    Result: ORA-06502: PL/SQL: numeric or value error: cannot assign supertype instance to subtype
    My question: in both cases the function f_60 is called in (it seems for me) the same condition. I mean in both cases the f_60 is called from a null object. Why the result differs then?
    Thanks for any help on this.
    Claude

    You can do this by creating a string which is the full sql statement
    and the executing it in PL/SQL.
    For example, you have str1 := 'SDO_GEOMETRY(2006, 600000, NULL, SDO_ELEM_INFO_ARRAY(1, 2, 1, 13, 2, 1), SDO_ORDINATE_ARRAY(196741, 219623, 196743, 219623, 196745, 219623, 196746, 219637, 196742, 219639, 196741, 219623, 196746, 219637, 196746, 219637, 196746, 219637, 196746, 219637)) ';
    Then make a SQL statement like this:
    str2 := 'INSERT INTO new_linestrings (id,geom,orig_id) values ' || '('|| to_char(se_new_linestrings.nextval)|| ', ' ||str1|| ', ' ||to_char(orig_id) ') ';
    execute immediate str2;
    ====
    you may have to read in se_new_linestrings.nextval to a local variable
    first.
    siva

  • Pl/sql block is too slow, should  procedure a better option

    Hi all,
    how to tune A PL/SQL block that traverse cursors and fetch millions of records then execute inserts in different tables,
    using execute immediate statement.
    It's too slow and takes 10 hours to populate 40 tables having millions of records,
    as i have to do some modifications in data so can not do it by CTAS,
    i.e. a single sql statement.
    Should i make a procedure, does it help .
    Please help or suggest As i am New to PL/Sql
    My code look like,
    declare
    cursor     cur_table1 is
         select field1,field2,field3,field4 from table1;
    begin
    for i in cur_table1
    loop
         execute immediate 'insert into table2 (field1,field2,field3,field4) '||
    'select :1,field2,field3,field4 '||
    ' from table1 where field3= :2'
    using i.field1||'_'||to_char(sysdate,'ddmmyyyy hh12:mi:ss',i.field1;
    commit;
    end if;
    end;
    Thanks and Regards,

    declare
    cursor cur_projects is
         select PROJECTID, PROJECTNAME, DESCRIPTION, DELETED, DELETINGDATE, ACTIVE, ADMINONLY, READONLY, SECURITYCLASS, PROJECTCONTACT, DEFAULTVERSION, DEFAULTSTARTPAGE, IMAGEPATH, MAXEXAMINEERRORS, LOCKTIMEOUT, MEMORYSAVINGLEVEL, PRELOADOBJECTS, PUBLICATIONSRCPROJNAME, CREATOR, CREATED, MODIFIER, MODIFIED from projects ;
    cursor cur_projectversion(p_projectid projects.projectid%TYPE) is
         select PROJECTID, PROJECTVERSIONID, PROJECTVERSIONNAME, DESCRIPTION, DELETED , DELETINGDATE, ACTIVE , ADMINONLY, READONLY, decode(EFFECTIVEDATE,null,trunc(sysdate),EFFECTIVEDATE) EFFECTIVEDATE, EXPIRATIONDATE, SECURITYCLASS, PROJECTCONTACT, DEFAULTVERSION, DEFAULTSTARTPAGE, IMAGEPATH, MAXEXAMINEERRORS, LOCKTIMEOUT, MEMORYSAVINGLEVEL, PRELOADOBJECTS, PUBLICATIONSRCPROJNAME, PUBLICATIONSRCPROJVERNAME, CREATOR, CREATED, MODIFIER, MODIFIED, PROFILELOADERCLASS /*, TRACKCHANGES */
         from projectversions where PROJECTID=p_projectid ;
    cursor cur_objects(p_projectid projects.projectid%TYPE,p_projectversionid projectversions.projectversionid%TYPE) is
         select PROJECTID , PROJECTVERSIONID, OBJECTID , OBJECTKEY , PARENTID, KIND , NAME , TITLE , OWNER , CREATED, MODIFIER , MODIFIED , READY_TO_PUBLISH, LAST_PUBLISHED_DATE , LAST_PUBLISHER , EFFECTIVE_PUBLISHING_DATE , PUBLISHER , PUBLISHING_DATE /*, to_lob(scripttext) */ from OBJECTS where PROJECTID=p_projectid and PROJECTVERSIONID=p_projectversionid /*order by objectid */;
    begin
    for i in cur_projects
    loop
    dbms_output.put_line('PROJECTID => '||i.projectid);
    dbms_output.put_line('_________________________________');
    execute immediate 'insert into &TARGET_USER\.projects(locktimeout, memorysavinglevel , preloadobjects, projectid, projectname, description, deleted, deletingdate, active, adminonly, readonly, securityclass, projectcontact, defaultversion, defaultstartpage, imagepath, maxexamineerrors ) values (:1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15,:16,:17) '
    using i.locktimeout, i.memorysavinglevel, i.preloadobjects,i.projectid ,i.projectname , i.description , i.deleted , i.deletingdate , i.active , i.adminonly , i.readonly, i.securityclass, i.projectcontact , i.defaultversion, i.defaultstartpage , i.imagepath, i.maxexamineerrors;
    for k in cur_projectversion(i.projectid)
         loop
    for l in cur_objects(k.projectid,k.projectversionid)
              loop
                   cnt:=cnt+1;
    select count(1) into object_exists from &TARGET_USER\.objects where objectid=l.objectid and projectversionid=1 and projectid=l.projectid;
              if object_exists = 0
              then
              if l.objectid = 1 ------Book Object , objectid = 1 and parentid = 0
              then
              execute immediate 'INSERT INTO &TARGET_USER\.objects(PROJECTID,PROJECTVERSIONID,OBJECTID, OBJECTKEY,PARENTID,NAME, KIND,LAST_PUBLISHED_DATE,LAST_PUBLISHER,REVISIONID,DISPLAYORDER,READONLY,DELETED) values( :1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13)'
                        using l.PROJECTID, 1, l.OBJECTID,l.OBJECTKEY, 0 , l.NAME,l.KIND, '' , '' , '', 0, 'N', 'N';
                   else
                        select count(1) into object_parentid_exists from objects where objectid=l.parentid and projectversionid=1 and projectid=l.projectid;
                        if object_parentid_exists = 0 ---Set Parentid as 1
                        then
                                  cnt_parentid_1:=cnt_parentid_1+1;
                                  execute immediate 'INSERT INTO &TARGET_USER\.objects(PROJECTID,PROJECTVERSIONID,OBJECTID, OBJECTKEY,PARENTID,NAME, KIND,LAST_PUBLISHED_DATE,LAST_PUBLISHER,REVISIONID,DISPLAYORDER,READONLY,DELETED) values( :1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13)'
                                  using l.PROJECTID, 1, l.OBJECTID,l.OBJECTKEY, 1 , l.NAME,l.KIND, '' , '' , '', 0, 'N', 'N';
                        else
                                  execute immediate 'INSERT INTO &TARGET_USER\.objects(PROJECTID,PROJECTVERSIONID,OBJECTID, OBJECTKEY, PARENTID, NAME, KIND,LAST_PUBLISHED_DATE,LAST_PUBLISHER,REVISIONID,DISPLAYORDER,READONLY,DELETED) values( :1,:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13)'
                                  using l.PROJECTID, 1, l.OBJECTID,l.OBJECTKEY,l.PARENTID,l.NAME,l.KIND, '' , '' , '', 0, 'N', 'N';
                        end if;
                   end if ;
         end if;
                   execute immediate 'INSERT INTO &TARGET_USER\.objectversions( PROJECTID, OBJECTID, PROJECTVERSIONID ,VERSIONNAME,OBJECTVERSIONID, REVISIONID,DESCRIPTION, TITLE , OWNER, CREATED, MODIFIER, MODIFIED, READY_TO_PUBLISH , LAST_PUBLISHED_DATE, LAST_PUBLISHER, EFFECTIVEDATE, SCRIPTTEXT, REVIEWSTATUS, READONLY, PUBLISHED, DELETED ) '||
                             'SELECT PROJECTID, OBJECTID, 1, owner||:1, PROJECTVERSIONID , '''', '''', TITLE, OWNER, CREATED, MODIFIER, MODIFIED, ''N'', '''' , '''', :2 , to_lob(SCRIPTTEXT), '''', ''N'', ''N'', '''' '||
                             'FROM OBJECTS '||
                             'WHERE PROJECTID= :3 and PROJECTVERSIONID= :4 and OBJECTID= :5'
                             using '_'||TO_CHAR(k.EFFECTIVEDATE,'DDMMYYHHMISS'),k.EFFECTIVEDATE,l.projectid,l.projectversionid,l.objectid;
         end loop;
         dbms_output.put_line(cnt||' OBJECTS, OBJECTVERIONS POPULATED');
         dbms_output.put_line(cnt_parentid_1||' DUMPED UNDER BOOK FOLDER ');
         cnt_parentid_1:=0;
         cnt:=0;
    ............

Maybe you are looking for