PL/SQL dynamic insert using cursor

Hello all,
I'm having big performance issues with (as you'll see below, a very simple) stored procedure. Any hints/suggestions would be really appreciated. Query below in the Loop is used to create a list of all months that fall within a member's start_date & end_date for insertion to member_months table. Can anyone suggest maybe a different approach to improve run time? It was timing out just using SQL, thought I might try PL. Thanks for anyone's help.
CREATE OR REPLACE PROCEDURE proc_MEMBER_MONTHS authid current_user as
/* get all Master member id's for cursor */
CURSOR c_unique_mmi IS
    select distinct master_member_id
    from member;
v_mmi                           member.master_member_id%TYPE;
BEGIN
dbms_output.enable(null);
   OPEN c_unique_mmi;
    LOOP
        FETCH c_unique_mmi INTO v_mmi;   /* pass mmi in cursor to variable */
        EXIT WHEN c_unique_mmi%NOTFOUND;
  INSERT INTO member_months   
      (mmi,                                        
      member_nbr,
      lob,
      member_month,
      member_year,
      member_month_count)
(SELECT master_member_id mmi,
        member_nbr,
        lob,
        month member_month,
        year member_year,
        ROW_NUMBER ()
          OVER (PARTITION BY member_nbr ORDER BY lob, year, month ASC)
          member_month_count
  FROM (SELECT DISTINCT
                   master_member_id,
                   member_nbr,
                   lob,
                   TO_CHAR (ADD_MONTHS (eligibility_start_date, LEVEL - 1), 'MM')
                      as MONTH,
                   TO_CHAR (ADD_MONTHS (eligibility_start_date, LEVEL - 1),
                            'YYYY')
                      as YEAR
              FROM (SELECT *
                      FROM mmi_data
                     WHERE master_member_id = v_mmi)              /* v_mmi is current MMI variable passed from cursor */
        CONNECT BY LEVEL <=
                        MONTHS_BETWEEN (TRUNC (eligibility_end_date, 'MM'),
                                        TRUNC (eligibility_start_date, 'MM'))
                      + 1));
    commit;
    END LOOP;
    CLOSE c_unique_mmi;
END;
/Edited by: BluShadow on 08-Aug-2012 14:03
added {noformat}{noformat} tags for readability.  Please read {message:id=9360002} and learn to do this yourself.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

All you would need is a direct insert like this
     insert into member_months   
            mmi
          , member_nbr
          , lob
          , member_month
          , member_year
          , member_month_count
      select   master_member_id mmi
          , member_nbr
          , lob
          , member_month
          , member_year
          , row_number () over (partition by member_nbr order by lob, year, month asc) member_month_count
        from (
            select distinct master_member_id
                , member_nbr
                , lob
                , to_char (add_months (eligibility_start_date, level - 1), 'mm') as member_month
                , to_char (add_months (eligibility_start_date, level - 1), 'yyyy') as member_year
              from (
                  select *
                    from mmi_data
                    join (
                        select distinct master_member_id v_mmi
                          from member
                      on master_member_id = v_mmi
           connect
                by level <= months_between (trunc (eligibility_end_date, 'mm'), trunc (eligibility_start_date, 'mm'))+ 1
          );Your procedure should have only this nothing else. Drop the cursor and looping.
If you want help in tuning the above query please give us the following details.
1. DB Version.
2. Execution Plan
3. Table Details (Number of rows)
4. Index Details

Similar Messages

  • Adding pagination in report build from PL/SQL dynamic content using htp.p

    Hi,
    I have a requirement for which i used PL/SQL dynamic content to build my report and i displayed my report using a cursor and loop by HTP.P function.
    Now problem is I have report with more than 500 rows and I want to add pagination concept for this report.
    How can i do that?
    Thanks in advance.
    Regards,
    Smith

    To preserve heading on each page for a HTML table you can use the THEADER, TFOOTER and TBODY tags (see example). To force page breaks, try experimenting with these style attributes:
    <STYLE TYPE="text/css">
         tr.breakhere {page-break-before: always}
    </STYLE>
    <tr class="breakhere">Table Example:
    htp.tableopen;
    htp.print('<THEAD style="display:table-header-group">');
    ... your table headers here
    htp.print('</THEAD>');
    htp.print('<TFOOT style="display:table-footer-group"><TR><TD></TFOOT>');
    htp.print('<TBODY>');
    ... your rows here
    htp.print('</TBODY>');
    htp.tableclose;Edited by: crokitta on Apr 8, 2009 2:07 PM

  • SQL or PL/SQL : dynamically insert table name in a SQL Statement

    Hi,
    We have a strange requirement - we need to dynamically use the table names in a SQL Query. E.g:
    select * from :table_name
    The table_name will be chosen from a list. I have tried this in SQL as well as PL SQL - but, I have been unsuccessul so far.
    Can you guys please help me solve this puzzle ?
    I hope I have explained my quesion clearly - if not, please do let me know if some more details are necessary.
    Regards,
    Ramky

    The following is the anonymous block that im using in a report in HTMLDB. My problem is Line Number 9. The bind variable contains the chosen table name at
    the run time.
    Variable "qry_stmt" contains the query to be returned, so that result set for that query will be displayed in the report.
    If I hard code the table name(rather that passing it through bind variable) in the
    qry_stmt string, Im getting the result sets for that query. But if I pass through
    bind variable at run time, its still generating the string correctly( im printing
    using a print statement at line number 14). But its returing the following report
    error
    report error:
    ORA-01403: no data found
    Please advice/help me in this.....
    declare
    qry_stmt varchar2(1000);
    p_table varchar2(30) := 'EMP';
    P_ENAME varchar2(1000);
    begin
    IF :p2_TABLE_NAMES IS NOT NULL THEN
    qry_stmt := 'select * from '||TRIM(:P2_TABLE_NAMES); -- Line Num 9
    execute immediate qry_stmt; --into P_ENAME;
    ELSE
    qry_stmt := 'SELECT 1 FROM dual ';
    END IF;
    htp.p(qry_stmt);--Line Num 14
    return qry_stmt;
    EXCEPTION WHEN NO_DATA_FOUND THEN
    NULL;
    end;
    Thanks and Regards,
    Ramky

  • How to Execute  sql query in PL/SQL ( a variable) with out using Cursor or REF cursor

    Hi
    I am building a dynamic query based on some conditions
    as an example
    v_query varchar2(2000);
    x1 varchar2(20);
    y1 varchar2(20);
    z1 varchar2(20);
    v_query := ' Select x,y,z into x1,y1,z1 From ... ';
    Is there any way to execute the query with out using cursor or ref cursor..
    Thanks
    Arun

    Both Tod and Eric provided valid responses given the format of the queory you supplied. Howver, if you want to use dynamic sql in either way, you need to be absolutely certain that your query will always only return a single row (e.g. SELECT COUNT(*) FROM mytable), because if it retuns more than one, your procedure will break unless you have an exception handler to handle either TOO_MANY_ROWS or OTHERS.
    If you want to pull in a lot of data without walking a cursor, you should look at the BULK COLLECT options.

  • Insert multiple rows using Cursors.

    I am trying to insert rows into a table based on information from another table.
    For example:
    When Table 1: Num_Rows = 100 my proc will insert 100 rows into Table 2 with relevent data.
    Do I need to use a Cursor and iterate through Num_Rows doing an INSERT each time? Is there a better way to do it other than using Cursors?
    Rob.

    It is not about using cursors or not using cursors. All SQLs wind up as cursors in the Oracle Shared Pool. So there is no such concept as not using cursors. Oracle needs to parse and compile and execute SQLs as cursors.
    The issue is WHERE* you do the work?
    Do you use the cursor (SQL) to do it for you? Or do you pull the data into another language, like PL or Java and process it there?
    And the performance mantra in this case is a very fundemantal Maximize SQL and minimize PL/Java/etc+.
    So do not do in PL/SQL what you can do in SQL only. It is a lot slower to pull data from the SQL engine into the PL engine. And then push that very same data from the PL engine back to the SQL engine. Like the following for example:
    -- poor design, poor performance
    for employee in (select e.* from emp e where e.deptid = 123 )
    loop
      insert into tab2 values( employee.empid, employee.name );
    end loop;You do not need to use PL (or Java) in this case. The SQL language is more than able to do this better and faster than any other language... as it is closer to the data.
    So the following is far more optimal code. Instead of the above PL/SQL code, we can simply do it as:
    -- optimal design: maximizing SQL and letting it to as much of the work as possible
    insert into tab2 select e.empid, e.name from emp e where e.deptid = 123;

  • Using cursor function in sql statement

    hi all
    can anyone plss explain why and when we will use cursor function in a sql statement like this and what is the difference while executing this sql statement with cursor function in comparison of a simple sql statement----
    select
    department_name,
    cursor (
    select last_name
    from employees e
    where e.department_id = d.department_id
    order by last_name
    ) the_employees
    from departments d
    thnx in advance

    RTFM
    http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14261/sqloperations.htm#sthref1452
    Cheers
    Sarma.

  • PL/SQL Using Cursor to Update Another Cursor

    Dear all,
    i am trying to do the below process ..i just wrote this code as an example ..can anyone give me idea how to acheive
    this .. i attached the error msg i am getting below ..
    CREATE OR REPLACE PROCEDURE EMP_COMPARE
    AS
    CURSOR c_emp_err
    IS
    SELECT EMPNO FROM EMP_ERR;
    CURSOR c_emp_cur
    IS
    SELECT EMPNO,FRST_NAME,LAST_NAME
    FROM EMP WHERE DEPTNO=20;
    BEGIN
    FOR r_emp IN c_emp_cur
    LOOP
    IF r_emp.EMPNO NOT IN(c_emp_err) --DONT PICK THE EMP'S WHICH ARE IN ERROR TABLE
    THEN
    UPDATE EMP SET APPLY_DATE=SYSDATE
    WHERE EMPNO=r_emp.EMPNO;
    END IF;
    END LOOP;
    END;
    ERR: PLS-00320: the declaration of the type of this expression is incomplete or malformed
    Thanks in Advance ...

    Hi,
    I see.
    My answer still applies: don't use cursors if you don't have to. Look for a way to do what you need to using just SQL statements.
    If you really do have to use two cursors, where some values in one are taken from the other, you can have nested cursors.
    For exampe, using scott's tables, say you want to give a 10% salaray raise to everyone in any department based in a given city.
    You could have two cursors:
    (1) find each department based in the right city
    (2) find each employee in the current department from (1)
    CREATE OR REPLACE PROCEDURE     slow_update
    (     in_city_name     IN     VARCHAR2
    AS
         CURSOR     dept_csr     (target_loc     VARCHAR2)
         IS     SELECT     deptno
              FROM     dept
              WHERE     loc     = UPPER (target_loc);
         CURSOR     emp_csr     (target_deptno     NUMBER)
         IS     SELECT     empno
              FROM     emp
              WHERE     deptno     = target_deptno;
    BEGIN
         FOR     dept_rec IN dept_csr (in_city_name)
         LOOP
              FOR     emp_rec IN emp_csr (dept_rec.deptno)
              LOOP
                   UPDATE     emp
                   SET     sal     = sal * 1.1
                   WHERE     empno     = emp_rec.empno;
              END LOOP;
         END LOOP;
    END     slow_update;Notice how I used parameters in the cursors.
    You would run the procedure like this:
    EXECUTE  slow_update ('Dallas');Repeat: This is for demonstration purposes only.
    The smart way to do such an UPDATE doesn't require cursors or PL/SQL:
    UPDATE     emp
    SET     sal     = sal * 1.1
    WHERE     deptno     IN     (
                   SELECT     deptno
                   FROM     dept
                   WHERE     loc     = UPPER (:target_city_name)
                   );

  • How to select data from 3rd row of Excel to insert into Sql server table using ssis

    Hi,
    Iam having Excel files with headers in first two rows , i want two skip that two rows and select data from 3rd row to insert into Sql Server table using ssis.3rd row is having column names.

                                                         CUSTOMER DETAILS
                         REGION
    COL1        COL2        COL3       COL4           COL5          COL6          COL7
           COL8          COL9          COL10            COL11      
    1            XXX            yyyy         zzzz
    2            XXX            yyyy        zzzzz
    3           XXX            yyyy          zzzzz
    4          XXX             yyyy          zzzzz
    First two rows having cells merged and with headings in excel , i want two skip the first two rows and select the data from 3rd row and insert into sql server using ssis
    Set range within Excel command as per below
    See
    http://www.joellipman.com/articles/microsoft/sql-server/ssis/646-ssis-skip-rows-in-excel-source-file.html
    Please Mark This As Answer if it solved your issue
    Please Mark This As Helpful if it helps to solve your issue
    Visakh
    My MSDN Page
    My Personal Blog
    My Facebook Page

  • Building a report using "PL/SQL Dynamic Content" can I have it output PDF?

    Hi,
    I build several reports using the "PL/SQL Dynamic Content" region and htp.p().
    The output is exactly what the customer wants but they would now like to have it go into PDF document.
    Is there a way to do it?
    Bill

    Bill,
    You can integrate APEX with Oracle BI Publisher and have your report generated to PDF.
    If you're just interested in saving what is on a web page in PDF, have a look at CuteFTP (Windows), which is a free print driver that allows you to "print" to a PDF file as if it were a printer. On the Mac, you can save to PDF and do not need any additional software.
    Thanks,
    &#150; Scott &#150;
    http://spendolini.blogspot.com/
    http://sumnertech.com/

  • Using SQL*PLUS Insert ??

    oracle 10G, using command line SQL*PLUS.
    I want to make 10 insert at a time, USING the ED mode.
    I want to load this into SQL
    ie insert ..;
    insert...;
    insert ..;
    commit ;

    Here is an example for a windows client.
    If you type 'ed' at the sql prompt and hit enter key, an editor window will show up. Type all your statements.
    Use the 'Save as' option from the 'file' menu to save the file (for example, 'abc.sql'). Close the editor. At the sql prompt, type '@path\abc' or 'start path\abc'.

  • Dynamic SQL Command Queries Using Parameters

    Post Author: tdoman
    CA Forum: Data Connectivity and SQL
    I'm using Crystal Reports 11 and am trying to dynamically build part of the "Where" clause in the SQL command query to filter data on the server before the results are sent to the client. I'm doing this to decrease the load time of my reports by not having to send a large set of data to the client, then filter the results on the client side.
    I want to create a parameter list that is dynamically generated from a table in a database and allows you to select mutiple values from that list. For example: I have two tables. One employee table and one employee type table. The employee table lists all employees and their related employee types (full-time, part-time, and contractor). The employee type table lists the employee types that will dynamically be loaded into the parameters list.
    Employee Table
    ID    Name       TypeID
    1     Bob          2
    2     Steve        1
    3     John         3
    4     Bill            1
    Employee Type Table
    ID   Type
    1     Full-Time
    2     Part-Time
    3     Contractor
    Assuming the user selects u2018Full-Timeu2019 and u2018Contractoru2019 from the parameter list, the SQL command query I want to generate is as follows:
    SELECT *
    FROM emp, emp_type
    WHERE emp.ID = emp_type.ID and emp.TypeID in (u20181u2019, u20183u2019)
    I tried building the following SQL command query so it would dynamically replace {?EmpType} with the IDu2019s of the types the user selected but it doesnu2019t work. Any ideas how to fix this?
    SELECT *
    FROM emp, emp_type
    WHERE emp.ID = emp_type.ID and emp.TypeID in ({?EmpType})

    Post Author: tdoman
    CA Forum: Data Connectivity and SQL
    btw...I just realized I had a typo in my "where" clause of the previous example. It should have been like so:WHERE emp.TypeID = emp_type.ID and emp.TypeID in (u20181u2019, u20183u2019)  satish_nair31:
    Instead of passing the filter condition as parameter it would be fine if you pass it by ReportViewer.SelectionFormula Property.
    The selection formula property of report viewer control will dynamically append the where condition with the SQL value. You will pass the filter condition as per the syntax of language supported by crystal reports.I believe using the ReportViewer.SelectionFormula property you are referring to is only available if I'm loading the report through a VB application. If this is true, then this option will not work for me because I'm loading the report in a browser from the Crystal Report web server and currently don't have a VB application that can load the report. If I did, then I could dynamically build the SQL string using VB then pass it to the Crystal Report on the fly.But I'm trying to figure out if it's possible to do it without loading the report using VB. Please correct me if I'm wrong on these assumptions.

  • Retreiving data from external DB using cursors (Native SQL)

    Hi experts,
    Iu2019m trying to use some functionality based on the Native SQL on an Oracle Server. Iu2019m facing some difficulties using cursors and fetching data from the external database.
    Basically the synonym its zfisicc_c_dblink, and Iu2019m running the for the following code:
    TRY.
          OPEN CURSOR WITH HOLD c1 FOR SELECT *
                                FROM  zfisicc_c_dblink
                                WHERE estado_sif = 'I'.
        CATCH cx_sql_exception INTO sqlerr_ref.
          PERFORM handle_sql_exception USING sqlerr_ref.
      ENDTRY.
    DO.
    *  "Move the data from the Cursor into the target area.
        FETCH NEXT CURSOR c1 APPENDING TABLE tab.
        IF sy-subrc  0.
          EXIT.
        ENDIF.
      ENDDO.
      CLOSE CURSOR c1.
    The cursor C1 it's cursor type and the table tab it's ZFISICC_C_DBLINK type, but every time i run it it's giving me the ORA-932 error.
    Database error text........: "ORA-00932: inconsistent datatypes: expected %s
    got %s"
    Can anyone help me on this error? What Iu2019m doing wrong when fetching the data ?
    Another doubt that Iu2019ve it's when using pl/Sql procedure. Can anyone tell how I can retrieve data from the external database with the following code?
    **Select Directo com Cursor
      EXEC SQL.
        CONNECT TO :gv_db_name AS 'dblink_con'
      ENDEXEC.
      IF sy-subrc NE 0.
        WRITE: 'Não foi possível fazer a ligação à DBCON: ', gv_db_name.
      ELSE.
        EXEC SQL.
          DECLARE CURSOR c_1 IS SELECT tipo_operacao FROM movimento_contribuicao
                 WHERE ROWNUM <= 10000;
              wa movimento_contribuicao.tipo_operacao%type;
    BEGIN
           OPEN c_1;
         LOOP
            FETCH c_1 INTO wa; "Not able to return data to SAP system
             EXIT WHEN c_1%NOTFOUND;
          END LOOP;
      END;
        ENDEXEC.
          EXEC SQL.
          DISCONNECT 'dblink_con'
        ENDEXEC.
      ENDIF.
    On the FETCH c_1 INTO wa; code Iu2019m moving the data to an Oracle variable, wa movimento_contribuicao.tipo_operacao%type;, and not to an program variable. Can anyone explain me this how this is +possible using this PL/SQL procedure?
    Thanks in advance,
    Best Regards
    João Martins
    Edited by: Rob Burbank on May 7, 2010 10:25 AM

    Hi Joao,
    Regarding your first question: It looks like there's a conversion problem (with one or more columns) from your Oracle table to your ABAP internal table.
    In the following link you can see (in your case in the SELECT section) the type conversions used for each type combination.
    Some combinations lead to an oracle error (specified in the "Result" column), like in your case (error 932).
    http://help.sap.com/saphelp_470/helpdata/EN/a3/74caa1d9c411d1950e0000e8353423/content.htm
    Regarding your second question: You can use the PERFORMING addition in the EXEC SQL statement.
    You can see an example in the following link:
    http://help.sap.com/saphelp_470/helpdata/EN/fc/eb3b8b358411d1829f0000e829fbfe/content.htm
    Hope it helps.
    Regards,
    Ana Luisa.

  • To Use  Cursor or  TYPE table Index by PLS_integer

    Hi All,
    Let's see if I have table with no. of records 19,26,20,000.
    If I want to loop through all the records which will be a optimized way To Use Cursor or TYPE table Index by PLS_integer.
    Please guide.
    Thanks.

    What is it you want to do to/with the rows you're looping through?
    Ideally you want to avoid looping, as that's row by row (aka slow by slow) processing and it's expensive time-wise.
    If you're doing DML (insert/update/delete) then you're best off doing it in one sql statement, rather than looping.

  • Why use cursor and for loop?

    Hi All
    So in general why would we use a cursor and a for loop to do update in a stored procedure?
    Why wouldnt we just use a single update statement ?
    is there compelling reason for using a cursor and a for loop: I am reading some code from a co-worker that the business logic for the select (set need to be updated) is complex but the update logic is simple (just set a flag to (0 or 1 or 2 or 3 or 4).
    But eventually the select come down to a key (row_id) so I re-write it using just a single sql statement.
    The size of the main table is about 2.6 to 3million rows
    Any thoughts on that??
    The code below I just do a google for cursor for update example in case for something to play with
    -Thanks for all your input
    create table f (a number, b varchar2(10));
    insert into f values (5,'five');
    insert into f values (6,'six');
    insert into f values (7,'seven');
    insert into f values (8,'eight');
    insert into f values (9,'nine');
    commit;
    create or replace procedure wco as
      cursor c_f is
        select a,b from f where length(b) = 5 for update;
        v_a f.a%type;
        v_b f.b%type;
    begin
      open c_f;
      loop
        fetch c_f into v_a, v_b;
        exit when c_f%notfound;
        update f set a=v_a*v_a where current of c_f;
      end loop;
      close c_f;
    end;
    exec wco;
    select * from f;
    drop table f;
    drop procedure wco;
    Joining multiple tables
    create table numbers_en (
      id_num  number        primary key,
      txt_num varchar2(10)
    insert into numbers_en values (1, 'one'  );
    insert into numbers_en values (2, 'two'  );
    insert into numbers_en values (3, 'three');
    insert into numbers_en values (4, 'four' );
    insert into numbers_en values (5, 'five' );
    insert into numbers_en values (6, 'six'  );
    create table lang (
       id_lang   char(2) primary key,
       txt_lang  varchar2(10)
    insert into lang values ('de', 'german');
    insert into lang values ('fr', 'french');
    insert into lang values ('it', 'italian');
    create table translations (
      id_num    references numbers_en,
      id_lang   references lang,
      txt_trans varchar2(10) not null
    insert into translations values (1, 'de', 'eins'   );
    insert into translations values (1, 'fr', 'un'     );
    insert into translations values (2, 'it', 'duo'    );
    insert into translations values (3, 'de', 'drei'   );
    insert into translations values (3, 'it', 'tre'    );
    insert into translations values (4, 'it', 'quattro');
    insert into translations values (6, 'de', 'sechs'  );
    insert into translations values (6, 'fr', 'six'    );
    declare
      cursor cur is
          select id_num,
                 txt_num,
                 id_lang,
                 txt_lang,
                 txt_trans
            from numbers_en join translations using(id_num)
                       left join lang         using(id_lang)
        for update of translations.txt_trans;
      rec cur%rowtype;
    begin
      for rec in cur loop
        dbms_output.put (
          to_char (rec.id_num         , '999') || ' - ' ||
          rpad    (rec.txt_num        ,   10 ) || ' - ' ||
          rpad(nvl(rec.txt_trans, ' '),   10 ) || ' - ' ||
                   rec.id_lang                 || ' - ' ||
          rpad    (rec.txt_lang       ,   10 )
        if mod(rec.id_num,2) = 0 then
          update translations set txt_trans = upper(txt_trans)
           where current of cur;
           dbms_output.put_line(' updated');
        else
          dbms_output.new_line;
        end if;
      end loop;
    end;
    /Edited by: xwo0owx on Apr 25, 2011 11:23 AM

    Adding my sixpence...
    PL/SQL is not that different from a SQL perspective than any other SQL client language like Java or C# or C/C++. PL/SQL simply integrates the 2 languages a heck of a lot better and far more transparent than the others. But make no mistake in that PL/SQL is also a "client" language from a SQL perspective. The (internal) calls PL/SQL make to the SQL engine, are the same (driver) calls made to the SQL engine when using Java and C and the others.
    So why a cursor and loops in PL/SQL? For the same reason you have cursors and loops in all these other SQL client languages. There are the occasion that you need to pull data from the SQL engine into the local language to perform some very funky and complex processing that is not possible using the SQL language.
    The danger is using client cursor loop processing as the norm - always pulling rows into the client language and crunching it there. This is not very performant. And pretty much impossible to scale. Developers in this case views the SQL language as a mere I/O interface for reading and writing rows. As they would use the standard file I/O read() and write() interface calls.
    Nothing could be further from the truth. SQL is a very advance and sophisticated data processing language. And it will always be faster than having to pull rows to a client language and process them there. However, SQL is not Turing complete. It is not the procedural type language that most other languages we use, are. For that reason there are things that we cannot do in SQL. And that should be the only reason for using the client language, like PL/SQL or the others, to perform row crunching using a client cursor loop.

  • Assigning a query dynamically to a cursor based on IF ELSE condotion

    hello guys,
    we are facing a problem while creating a procedure.
    The procedure has been recreated in ORACLE from SQL SERVER 2005.
    the problem is that in SQL server we can assign a query dynamically to a cursor so that it will be called at execution time.But this is not the case in oracle, i.e in Oracle its not allowed to assign a query to a cursor dynamically(OR IS IT...!!!)
    the code is
    vr_SQL varchar2(400);
    declare
       cursor ord_cur  ;  <-----cursor declaration
      begin
       If v_pIsScrutiny = 0 then   +<--------------second condition+
          vr_SQL:='Select NVL(ServiceID,0)  ServiceID,OrdQty,+<-------query assignment to a variable+
              NVL(DrugID,0) DrugID,NVL(ServiceAmount,0) Rate,OrdDtlID 
              from Orderdtl inner join ordermst on Orderdtl.OrdID = ordermst.OrdID 
              Where Orderdtl.OrdID in (Select OrdID From Ordermst Where OrdVisitID = vr_visitid  
              and TO_CHAR(ordermst.OrdDate,''DD-MON-YYYY'') 
              Between TO_CHAR(vr_pActivationDate,''DD-MON-YYYY'') 
              and TO_CHAR(vr_pExpiryDate,''DD-MON-YYYY'') 
              ) And NVL(Orderdtl.Cancelled,0) = 0 And NVL(Orderdtl.PackageID,0) = 0 
              and NVL(Orderdtl.DrugID,0) = 0;';
        Else  +<--------------first condition+
            Update OrderDtl Set PackageID = 0 , AllocationID = 0 , ConsumptionID = 0 
            Where OrdID in (Select OrdID From Ordermst Where OrdVisitID = vr_visitid)  
            And AllocationID = v_pHCPAllocationID; 
           vr_SQL:= 'Select NVL(ServiceID,0)  ServiceID, +<-------query assignment to a variable+
           OrdQty,NVL(DrugID,0)  DrugID,NVL(ServiceAmount,0)
            Rate,OrdDtlID 
           from Orderdtl inner join ordermst on Orderdtl.OrdID = ordermst.OrdID 
           Where Orderdtl.OrdID in (Select OrdID From Ordermst Where OrdVisitID = vr_visitid  
           and TO_CHAR(ordermst.OrdDate,''DD-MON-YYYY'') 
           Between TO_CHAR(vr_pActivationDate,''DD-MON-YYYY'') 
           and TO_CHAR(vr_pExpiryDate,''DD-MON-YYYY'') 
           ) And NVL(Orderdtl.Cancelled,0) = 0 And NVL(Orderdtl.PackageID,0) = 0;'; 
        end if;
           ord_cur is vr_SQL; +<----------query assigned to a cursor variable+
        ord_rec ord_cur%ROWTYPE;
       if not ord_cur%ISOPEN then
            open ord_cur;
       end if;
        loop
        fetch ord_cur into ord_rec;
        exit when ord_cur%NOTFOUND;So currently we are stuck with this problem.
    Any solution would be of great help..
    thank you

    841363 wrote:
    hello guys,
    we are facing a problem while creating a procedure.
    The procedure has been recreated in ORACLE from SQL SERVER 2005.
    the problem is that in SQL server we can assign a query dynamically to a cursor so that it will be called at execution time.But this is not the case in oracle, i.e in Oracle its not allowed to assign a query to a cursor dynamically(OR IS IT...!!!)The problem is that you are thinking in SQL Server terms and Oracle just isn't SQL Server.
    You need to consider using ref cursors for such things (sys_refcursor) e.g.
    SQL> CREATE OR REPLACE PACKAGE reftest IS
      2    PROCEDURE test(P_no in number, cur_o OUT sys_refcursor);
      3  end;
      4  /
    Package created.
    SQL>
    SQL> CREATE OR REPLACE PACKAGE body reftest as
      2    PROCEDURE test(P_no in number, cur_o OUT sys_refcursor) as
      3      myexc exception;
      4    BEGIN
      5      if P_no = 1 then
      6        open cur_o for select empno, ename from emp;
      7      elsif p_no =2 then
      8        open cur_o for select deptno, dname from dept;
      9      else
    10        RAISE myexc;
    11      END IF;
    12    exception
    13      when myexc then
    14        raise_application_error(20991,'input must be 1 or 2');
    15    end ;
    16  end reftest;
    17  /
    Package body created.
    SQL> var x refcursor;
    SQL> exec reftest.test(1,:x);
    PL/SQL procedure successfully completed.
    SQL> print x;
         EMPNO ENAME
          7369 SMITH
          7499 ALLEN
          7521 WARD
          7566 JONES
          7654 MARTIN
          7698 BLAKE
          7782 CLARK
          7788 SCOTT
          7839 KING
          7844 TURNER
          7876 ADAMS
          7900 JAMES
          7902 FORD
          7934 MILLER
    14 rows selected.
    SQL> exec reftest.test(2,:x);
    PL/SQL procedure successfully completed.
    SQL> print x;
        DEPTNO DNAME
            10 ACCOUNTING
            20 RESEARCH
            30 SALES
            40 OPERATIONS
    SQL>

Maybe you are looking for

  • Creating Popup Menu in Desktop Intelligence

    I need help creating a popup menu in the Tool menu of Deski. This popup needs to be visible when a report is open or when no report is open. It's my first add-in and I can't make my code work. Sub BuildMyMenu() Dim PopMenu As CmdBarControl Dim CleanP

  • Pointing KM to our file server

    Hi folks, We have recently setup a portal prototype and I have got KM working with the folders that exist on the portal server.  My question is can I point the KM to our file server that exists on our network?  Assuming I can do this, does the Check-

  • Assigning Different Spaces to Multiple Displays

    Hi, I have my Mac connected to my TV (not mirroring) and I'm using Spaces. I was wondering if it was possible to assign to each display, a different Space? In other words, can I have my Mac screen displaying Space 1, and my TV displaying Space 3? My

  • An error has occurred while attempting to load crystal report runtime 64

    I am using Crystal Report 2008. Visual Studio 2008 Professional on a SQL Server 2005 X64 SP2 with .NET 3.5 SP1 beta framework This problem happens in X64 environment only. I tried everything I Can find in the web: 1) run the crredist2008_x64 and X86.

  • Rmi applet , browser

    hi~ i have a rmi applet when i run the applet (use appletviewer) is ok but it's on bowser , can't work can anynoe tell me maybe what's problem how can i do thanks