Query within the Cursor loop is very slow

Hi ,
I have a stored procedure which has Select/Insert operation which is looped within the cursor. The Select uses variables from the cursor, and inserts the data into the table.
My problem is the peformance. The stored procedure executes in 2 mins if I hard code the where clause values in the Select. Instead if I use the variables obtained from the cursor, the query takes so long (more than 20 mins) to insert the same no of records into the table.
Below is the snippet of my code
create procedure sample is
declare
v_acct_month number(2);
v_sp_name varchar2(30);
cursor v_cur is Select distinct Acct_Month,salesperson_name from period;
begin
open v_cur;
loop
fetch v_cur into v_acct_month, v_sp_name;
exit when v_cur%notfound;
Insert into T1
Select * from T2,T3.. Where T2.month=v_acct_month,t3.sp_name=v_sp_name;
end loop;
End;
The query is not using the optimizer when the variables are used.The optimizer is used when I hard code the values in the select.
Please give me suggestions to make this query faster..
Thanks,
Arun
Edited by: [email protected] on Mar 28, 2009 10:18 AM

Hi,
Whenever you write code, format it to show the scope of BEGIN, LOOP, IF statements, and so on.
Type these 6 characters
{code}
(small letters only, inside curly brackets) before and after the formatted code, to preserve spacing on this site.
You've discovered why the tecnique you're using is called "slow-by-slow" processing.
You don't need a cursor. You may not even need PL/SQL.
Just write an INSERT statement that reference the table from the cursor and the tables from your current INSERT statement.
Here's one way:
INSERT
INTO     t1 (columns)
SELECT         columns
FROM     t2
,     t3
WHERE     ...
AND     (t2.month, t3.sp_name)     IN (
                          SELECT DISTINCT
                               acct_month
                       ,        salesperson_name
                       FROM        period
                       );Depending on the details of your case, there may be a better way, such as a 3-way join.

Similar Messages

  • The cursor movement is very 'slow' or 'inertial'

    Hi.
    I bought a mac mini with a magic mouse and connected it to a large LCD TV via HDMI (fullHD). Everything is excellent, save for the fact that the cursor movement is very 'slow' or 'inertial'.

    Hi,
    Whenever you write code, format it to show the scope of BEGIN, LOOP, IF statements, and so on.
    Type these 6 characters
    {code}
    (small letters only, inside curly brackets) before and after the formatted code, to preserve spacing on this site.
    You've discovered why the tecnique you're using is called "slow-by-slow" processing.
    You don't need a cursor. You may not even need PL/SQL.
    Just write an INSERT statement that reference the table from the cursor and the tables from your current INSERT statement.
    Here's one way:
    INSERT
    INTO     t1 (columns)
    SELECT         columns
    FROM     t2
    ,     t3
    WHERE     ...
    AND     (t2.month, t3.sp_name)     IN (
                              SELECT DISTINCT
                                   acct_month
                           ,        salesperson_name
                           FROM        period
                           );Depending on the details of your case, there may be a better way, such as a 3-way join.

  • Web pages slow to load with IE11 and the cursor/mouse is very slow to work until after page loads

    Web pages are very slow to load, I hve run Norton Eraser and found no issues that would cause this

    New HP Pavilion three weeks ago.  After several attempts by the 'experts' I finally got a straight answer from a tech in the Philipines yesterday, 01-29-2015.  HP and Microsoft are working to resolve the issue of slow pages and a dead cursor until the next page finally loads.  You may have discovered that Google Chrome DOES NOT have this issue.  Comments about HP would not be allowed here so I will just say, use Chrome until the issue with IE 11 is resolved.

  • With clause within the cursor ???

    Hello gurus,
    Can we have a with clause within the cursor ???
    something like this ..
    cursor test_cur is
    WITH unpivoted_data     AS
         SELECT DISTINCT
    f.cust_id
              f.office_cd
              f.type_cd
         FROM      refoff      ro,
              cutomer     p,
              office     f
         WHERE     f.cust_id     = p.cust_id
         AND     f.office_cd      = ro.office_cd
         AND      f.type_cd      IN ('ACCT', 'pay')
    SELECT     cust_id
    ,     MAX (CASE WHEN type_cd = 'ACCT' THEN office_id END)     AS acct_office_id
    ,     MAX (CASE WHEN type_cd = 'pay' THEN office_id END)     AS pay_office_id
    FROM     unpivoted_data
    GROUP BY cust_id
    test_cur_rec test_cur% rowtype;
    Begin
    for test_cur_rec in test_cur
    loop
    insert into test1 (.....) values (.......);
    end loop;
    end;
    One more quick question .... How do u guys past in the posting ??? Like somesought of a box .....I have seen lot senior gurus when they are replying, they post the code in some sought of a box ....that makes very easy to understand and take look at the code in the posting....???
    Thank you so much!!!

    Hi,
    user642297 wrote:
    Hello gurus,
    Can we have a with clause within the cursor ???Sure, but don't take my word for it. Try it and see!
    If you get an error, post the error message.
    If you get unexpected results, explain.
    Whenever you have a problem, post your full Oracle version number.
    One more quick question .... How do u guys past in the posting ??? Like somesought of a box .....I have seen lot senior gurus when they are replying, they post the code in some sought of a box ....that makes very easy to understand and take look at the code in the posting....??? Type these 6 characters:
    (all small letters, inside curly brackets) before and after formatted sections.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How can I create cursors within the cursor?

    How can I create cursors within the cursor?
    Table1 2001 - 2007 data
    Account_no
    Account_eff_dt
    No_account_holder
    Num
    Seq_Num
    Value1
    Value2
    Table2_Historical (doesn't have Num as a field) 1990 - 2000 data
    Account_no
    Account_eff_dt
    No_account_holder
    Seq_Num
    Value1
    Value2
    Table3_06
    Account_no
    Account_eff_dt
    No_account_holder
    Num
    My result table should be:
    Table_result_06
    Account_no
    Account_eff_dt
    No_account_holder
    Num
    Value1_min (the minimum value for the minimum of record_sequence)
    Value2_max (the maximum value for the maximum of record_sequence)
    I have to get data from Table1 and Table2_Historical. If one account was open in 1998 and is still effective, the minimum value of that account is in the Table2_Historical.
    Let's say I open a cursor:
    cursor_first is
    select * from table3_06;
    open csr_first
    loop
    fetch cursor_first into
    v_Account_no
    v_Account_eff_dt
    v_No_account_holder
    v_Num
    EXIT WHEN csr_first%NOTFOUND;
    How can I open a second cursor from here that will get the Seq_Num from Table1
    csr_second
    select Seq_Num from Table1 where
    v_Account_no = Account_no
    v_Account_eff_dt <= Account_eff_dt
    v_No_account_holder=No_account_holder
    v_Num = Num
    How does it works???
    Thanks a lot

    Thanks so much for replying back. Here is what I am trying to do.
    I have to create a table for each year 2002, 2003, 2004, 2005, 2006 that has all the account numbers that are active each year plus some other characteristics.
    Let’s say I will create Table_result_06. This table will have the following fields. The account number, account effective date, Number of the account holder and the field Num (The primary key is a combination of all 4 fields), the beginning look of value 1 in 2006, the last look of value 1 in 2006.
    Table_result_06
    Account_no key
    Account_eff_dt key
    No_account_holder key
    Num key
    Value1_min (the minimum value for the minimum of record_sequence)
    Value2_max (the maximum value for the maximum of record_sequence)
    All the active account numbers with the Account_eff_dt, No_account_holder and Num are in the Table3. As such I can build a query that connects Table3 with table Table1 on all 4 fileds, Account_no, Account_eff_dt, No_account_holder, Num and find the Value1_min for the min of req_sequence in 2006 and Value1_max for the max of req_sequence in 2006. Here my problem starts.
    Table 1 doesn’t have a new entry if nothing has changed in the account. So if this account was open in 1993 and nothing has changed I don’t have an entry in 2006 but this doesn’t mean that this account doesn’t exist in 2006. So to find the minimum value I have to go back in 1993 and find the max and min for that year and that will be max and min in 2006 as well.
    As such I have to go to Table_2 historical and search for min and max. But this table doesn’t have the field NUM and if I match only on the Account_no, Account_eff_dt and No_account_holder I don’t get a unique record.
    So how can I connect all three tables, Table 1 for max and min, if it doesn’t find anything will go to table 2 find the two values and populate Table_result_06.
    Thanks so much again for your hep,

  • Cursor within the cursor showing error

    Hi,
    I am using a cursor within the cursor to create a procedure.I am getting the below error while compiling this
    15/7 PL/SQL: SQL Statement ignored
    16/14 PL/SQL: ORA-00942: table or view does not exist
    79/10 PL/SQL: Statement ignored
    82/31 PLS-00364: loop index variable 'I' use is invalid
    84/10 PL/SQL: Statement ignored
    84/50 PLS-00364: loop index variable 'I' use is invalid
    98/10 PL/SQL: Statement ignored
    101/31 PLS-00364: loop index variable 'I' use is invalid
    103/10 PL/SQL: Statement ignored
    103/50 PLS-00364: loop index variable 'I' use is invalid
    Am i using a wrong syntax,Could anyone help me on this..Please find my procedure code below
    CREATE OR REPLACE PROCEDURE DM_EIS.YOY_PURGE_PRC
    AS
    VAR_TEMP NUMBER := 1;
    VAR_TAB_NAME VARCHAR2(100);
    VAR_TAB_OWNER VARCHAR2(100);
    --For fetching table list to be processed
    CURSOR CUR_ONE IS
    SELECT OWNER,TABLE_NAME,FILTER_DATE,FILTER_VALUE
    FROM DM_EIS.NONPART_PURGE_CTL WHERE NVL(STATUS,'NULL') <> 'COMPLETED'
    AND PURGE_PREFERENCE='Y';
    --For fetching indexs that are to be disabled
    CURSOR CUR_IND IS
    SELECT * FROM DBA_INDEXES WHERE TABLE_NAME = var_tab_name
    AND OWNER = var_tab_owner
    AND UNIQUENESS <> 'UNIQUE';
    BEGIN
    FOR C IN CUR_ONE
    LOOP
    --CHECK IF TEMP TABLE IS ALREADY PRESENT, IF SO DROP IT.
    SELECT COUNT(*) INTO VAR_TEMP FROM ALL_TABLES WHERE TABLE_NAME = 'T_NOPART_PURGE';
    IF VAR_TEMP = 1
    THEN
    EXECUTE IMMEDIATE 'DROP TABLE DM_EIS.T_NOPART_PURGE';
    END IF;
    ---update the columns of Control table
    UPDATE DM_EIS.NONPART_PURGE_CTL
    SET STATUS = 'RUNNING'
    WHERE TABLE_NAME = C.TABLE_NAME
    AND OWNER = C.OWNER;
    COMMIT;
    UPDATE DM_EIS.NONPART_PURGE_CTL
    SET START_TIME = SYSDATE
    WHERE TABLE_NAME = C.TABLE_NAME
    AND OWNER = C.OWNER;
    COMMIT;
    --Check whether the column value is date or year
    IF C.FILTER_VALUE = 'YEAR' THEN
    --Move data to temp table and truncate main table
    execute immediate 'create table DM_EIS.T_NOPART_PURGE as select /*+ PARALLEL(ext,4) */ ext.* from '||c.owner||'.'|| c.table_name || ' ext where nvl(' || c.FILTER_DATE || ',''01-Feb-2009'') >= ''2009''';
    DBMS_OUTPUT.PUT_LINE('Truncating the main table'||C.OWNER||'.'|| C.TABLE_NAME);
    EXECUTE IMMEDIATE 'TRUNCATE TABLE ' ||C.OWNER||'.'|| C.TABLE_NAME;
    else
    --Move data to temp table and truncate main table               
    execute immediate 'create table DM_EIS.T_NOPART_PURGE as select /*+ PARALLEL(ext,4) */ ext.* from '||c.owner||'.'|| c.table_name || ' ext where nvl(' || c.FILTER_DATE || ',''01-Feb-2009'') >= ''01-Jan-2009''';
    DBMS_OUTPUT.PUT_LINE('Truncating the main table'||C.OWNER||'.'|| C.TABLE_NAME);
    EXECUTE IMMEDIATE 'TRUNCATE TABLE ' ||C.OWNER||'.'|| C.TABLE_NAME;
    end if;
    var_tab_name := c.table_name;
    var_tab_owner := c.owner;
    --Disable the indexes and load data back to main table,
    for i in cur_ind
    loop
    execute immediate 'Alter index '||c.OWNER ||'.'|| i.index_name || ' unusable';
    dbms_output.put_line(c.OWNER ||'.'|| i.index_name||' is unusable');
    end loop;
    ---insert back the data into the table from temporary table
    execute immediate 'insert /*Append*/ into '||c.OWNER ||'.'|| c.table_name || ' select /* PARALLEL(tmp,4) */ tmp.* from DM_EIS.T_NOPART_PURGE tmp';
    commit;
    --Rebuild the indexes
    for i in cur_ind
    loop
    execute immediate 'Alter index '||c.OWNER ||'.'|| i.index_name || ' rebuild compute statistics';
    dbms_output.put_line(c.OWNER ||'.'|| i.index_name||' is rebuilt');
    end loop;
    --Gather stats for the table
    DBMS_STATS.GATHER_TABLE_STATS(OWNNAME=>c.OWNER,
    TABNAME=>c.table_name,
    CASCADE=>TRUE,
    ESTIMATE_PERCENT=>dbms_stats.auto_sample_size
    dbms_output.put_line(c.OWNER ||'.'|| c.table_name||' is analyzed');
    ---update the columns of Control table
    update DM_EIS.NONPART_PURGE_CTL
    set status = 'COMPLETED'
    where TABLE_NAME = c.TABLE_NAME
    AND OWNER = C.OWNER;
    commit;
    UPDATE DM_EIS.NONPART_PURGE_CTL
    SET END_TIME = SYSDATE
    WHERE TABLE_NAME = C.TABLE_NAME
    AND OWNER = C.OWNER;
    COMMIT;
    UPDATE DM_EIS.NONPART_PURGE_CTL
    SET ELAPSED_TIME =ROUND((END_TIME-START_TIME)*1440,2)
    WHERE TABLE_NAME = C.TABLE_NAME
    AND OWNER = C.OWNER;
    COMMIT;
    UPDATE DM_EIS.NONPART_PURGE_CTL
    SET LAST_UPDATED_DT = SYSDATE
    WHERE TABLE_NAME = C.TABLE_NAME
    AND OWNER = C.OWNER;
    COMMIT;
    dbms_output.put_line('Data Purging is done for '||c.OWNER ||'.'|| c.table_name);
    end loop;
    EXCEPTION
    WHEN OTHERS THEN
    RAISE_APPLICATION_ERROR(-20003,' ERROR IN DM_EIS.NONPART_PURGE_PRC'|| SQLCODE||'-'||SQLERRM);
    End;
    /

    Oracle is not a Microsoft product. What it appears you are doing is a phenomenally efficient way to bring your database to its knees whimpering and begging that you take a class from Oracle University.
    Temporary tables in Oracle are permanent tables and that is the proper design for working with the product. Creating "temp" tables using dynamic SQL in a stored procedure is multiple layers of bad practice layered on top of each other. Something made more obvious by the fact that you appear to not have read that portion of the docs that explain the differences between explicit privilege grants and grants made via roles when it comes to PL/SQL.
    My recommendation is that you throw this code away and read the docs. First on the security model, roles, and object privileges. Next on the use of Global Temporary Tables.

  • The popup LOV is very slow in APEX 4.0, did anyone can help on this?

    The popup LOV is very slow in APEX 4.0, did anyone can help on this?
    Wherever I try to open a popup LOV windows , I am always be very patient to wait the window show . Even if only a very few record to show.
    Edited by: daniel.luo on 2010/7/28 上午 7:52

    Hi Daniel,
    it probably doesn't matter how many records you show if you have an ORDER BY clause in your SQL statement. Because the database still has to do all the work to return you the first result set.
    Is the query itself fast if you execute it in "SQL Workshop"?
    Have you already tried the setting "Fetch" = "No Fetch"? Is the window now opening faster? I just want to rule out that it's a generic problem, but I think it has to do with your SQL statement.
    Was the popup LOV for this SQL statement faster in 3.2?
    Regards
    Patrick
    My Blog: http://www.inside-oracle-apex.com
    APEX 4.0 Plug-Ins: http://apex.oracle.com/plugins

  • Link aggregated between NAS and a switch: the Mac as a very slow access...

    Hello,
    in my Office we're working with Macs and PCs and all the data is on a NAS.
    Here is our configuration:
    NAS <-link1->Switch<-Link2->Macs or PC.
    Macs are connected with AFP protocol (because SMB is very slow).
    We want to use Link Aggregation between the NAS and the switch (with 802.3ad procotol) but when we do that all the Macs have a very slow access to the NAS. But all is OK with the PCs.
    What can we do? Is there a problem with macOS X and link aggregation?
    Thank you for your help.
    Nicolas

    Sorry, not sure what the question is exactly.
    You must have an Xserve, or Ethernet cards capable of Jumbo Frames for one, I assume the Switch & NAS are capable?
    Possible clues...
    http://docs.info.apple.com/article.html?path=ServerAdmin/10.4/en/c3ha3.html
    http://discussions.apple.com/thread.jspa?threadID=1715388&tstart=0
    http://www.macnn.com/articles/04/06/21/link.aggregation.for.macs/
    http://www.smallnetbuilder.com/content/view/30556/53/
    http://www.afp548.com/forum/viewtopic.php?showtopic=8309

  • Most of the crap ios 7 very slow I want to go back to ios 6.

    Most of the crap ios 7 very slow I want to go back to ios 6.

    Something may have gone amiss in the upgrade to iOS 7 on your iPhone.
    To correct this follow these steps:
    1. Backup your iPhone using iTunes or iCloud.
    2. Use iTunes to completely restore your iPhone as new.
    3. Monitor performance to see if it is normal. If not, you may have a hardware problem - if so, contact Apple support.
    4. Restore your iPhone from your backup above.
    5. Check performance to confirm that it remains normal.

  • Can you help me, i try to import video from my gopro to final cut pro but when i play the video he become very slow and i lose qualiter

    can you help me, i try to import video from my gopro to final cut pro but when i play the video he become very slow and i lose qualiter ???

    Right click one of yur clips in the event browser and choose Transcode Media. Make a test project and playthat clip. See whether that solves your lag.
    Russ

  • I have a problem when i am connecting my mbpr to a monitor , the internet is going very slow when i connect to the monitor plz help me if i buy a vga to minidisplay it will help??

    i have a problem when i am connecting my mbpr to a monitor , the internet is going very slow when i connect to the monitor plz help me if i buy a vga to minidisplay it will help??

    dovdov2,
    are you saying that when you connect your MacBook Pro to a monitor, your Internet connection slows down, but when you disconnect the monitor, it speeds up again, and that this is reproducible from one day to another?
    Does this happen both under OS X and under Windows 7, or only under one of them?
    How are you currently connecting your MacBook Pro to your monitor?

  • Backup to the remote stages is very slow

    Hello!
    I am facing with the following problem for DB Backup to the remote stage.
    If I plan the ALL ONLINE-Backup, then the backup is takes very slow, backups two or more files and aborts.
    I have checked the appropriate  BTC WP and saw that the WP is holding/waitng.
    The reason is RFC.
    How can the problem be solved?
    Thank you very much!
    regards
    Thom

    Without logs of the backups we can just guess, what is wrong.
    Post the log of a failed remote backup here and let´s see then.
    Markus

  • I have new mac the speed download is very slow

    i have new mac the speed download is very slow please let me know.

    The warranty entitles you to complimentary phone support for the first 90 days of ownership.
    If you bought the product in the U.S. directly from Apple (not from a reseller), you also have 14 days from the date of delivery in which to exchange or return it for a refund. In other countries, the return policy may be different. If you bought from a reseller, its return policy applies.

  • Cisco Unity Connection 8.0 / access to the user configuration is very slow

    Hello!!
    The access to the user configuration is very slow. When you click on an user it need about 2-3 minutes until the configuration sidewill be loaded.
    What could be the reason?
    How is it possible to load the user configuration a little bit faster?
    A restart of the Cisco Unity Connection was done.
    The user will be imported from the CallManager.
    Cisco Unity Connection 8.0.2.40000-12
    WebBrowser: Internet Explorer 8.0
    Same result with Mozilla Firefox 3.6
    Any ideas?
    Thank you!!!
    Joerg K.

    Hello Joerg,
    could it be possible that you have some problems with the AXL integration for example wrong /dead server IP:
    CSCth86004 Import page takes long time to load if AXL integration is broken
    http://tools.cisco.com/Support/BugToolKit/search/getBugDetails.do?method=fetchBugDetails&bugId=CSCth86004
    Kind regards,
    Marcel Ammann
    P.S.: Please rate helpful post's

  • Sending mail with "sent" is fast, but copying the sent mail is very slow, sometimes takes a minute; can it be speeded up?

    After hitting "send", a screen comes up showing a moving bar "copying the mail to the sent folder", the bar goes fully right on
    the screen but then I must wait, sometimes a minute for the copying process to complete. Then I always get a screen message
    next that says in effect could not copy, so I close that screen and then go to my sent folder and the email I sent shows up. So,
    the copy process is very slow and then I get a message could not copy, but in fact a copy does appear in sent folder????
    Thank you

    You do not mention how big is the Sent folder.
    I would first try to archive a load of old sent emails. This will reduce the file size. Maybe the delay is due to a large file.
    Set up Archive Options:
    * https://support.mozilla.org/en-US/kb/archived-messages
    choose to archive by month and year and keep folder structure.
    Archive anything older than a month.

Maybe you are looking for