Questions about CURSOR FOR... LOOP

Good evening

In reading the posts here, I came across a number of cases where it was clear that there is no special affection for the cursor for loops.

I googled... found around articles naming some minor inconveniences, but nothing which would justify the aversion towards them, I noticed here.

My questions are:

1. why the cursor for loops so undesirable?
2. What are alternative fuels?

Thank you for helping,

John.

Published by: 440bx - 11 GR 2 on August 12, 2010 21:23 - plural on the issue and remove superfluous in the subject.

Hey John,

http://asktom.Oracle.com/pls/asktom/f?p=100:11:0:P11_QUESTION_ID:760210800346068768

Has some good points on the subject.

Cursor loops are not "bad" per say, but they go against the philosophy of treatment in bulk (unless you do things like increase your cursor with BULK COLLECT and FORALL, that would go to point 2 in your question).

Basically, when you see a large number of cursor loops you get something like someone writing their own LOOPS IMBRIQUEES join inside pl/sql

for x in
(
   select * from table1
)
loop
   for y in
   (
      select * from table2 where table2.column1 = x.column1
   )
   loop
....

While you could just write a single SQL

   for x in
   (
      select x.columns, y.columns
      from table1 x, table2 y
      where x.column1 = y.column1
   )
   loop
      ....

The former removes a lot of options for optimization of Oracle queries can / could do since he doesn't see s a SQL both. You hit repeatedly table2 (probably via a sweep of index which means that you will get a single block IO as opposed to IO multiples of block that can be done for FULL TABLE SCAN) and remove any chance of Oracle doing the treatment 'fantasy' through things like the HASH JOINS (if the optimizer has determined the request was a good fit for one) etc...

In general, tie you the hands of the Oracles by dictating treatment rather than run through a whole considerable options to determine the best paths to the data you need.

You can find much better on the site, AskTom explanations, I hope that this is a decent Preview so :)

In Oracle 10 and better, Oracle will actually convert an implicit cursor (as I used above) in bulk, with a size of default array of 100 elements (you can measure this easily with a TKPROF and a simple implicit cursor). But that still won't help you much if you write your own nested loops join like I faked it above.

Published by: Tubby on August 12, 2010 18:51

Added a little more... too much to say on the subject, and not enough time :)

Tags: Database

Similar Questions

  • Question about the update of a cursor for loop

    Hi, please someone could help with the following:

    I have a simple script below:

    declare

    cursor c1 is select name, salary of employers;


    Start

    for rec loop c1

    dbms_output.put_line ('employee' |) Rec.Name | ' s former salary was £' | Rec.salary);

    update of employers set salary = salary * 1.2 where name = rec.name;


    dbms_output.put_line ('employee' |) Rec.Name | "new treatment is £' | Rec.salary);

    end loop;

    end;

    This gives me the old value of the salary, but the output for the new salary remains the same, that is to say, it has not increased by 1.2.

    Ive tried to run in the 2 loops that works, but does not give me in order I want, IE employers followed old sal nine.

    Ive tried to add is committed and various other things, but it makes no difference. I thought that the script above should work. Where I'm going wrong?

    Thank you very much

    882839 wrote:

    I learned (perhaps wrongly) that cursor for loops were good practice. Is it not the case?

    Could you mention who told you this?

    I'm curious because on a daily basis in almost all the sons of my treatment is slow , the reason for the slow transformation is the loop and all responses point out that you are using a loop ensures that the process is running more slowly as possible.

    But despite any response in this community saying loops are the worst practices, every day more people come here apparently having learned exactly the opposite and then wonder why their program runs like a dog three legs with an anchor attached to his tail.

  • When to use the cursor for loop and the cursor (open, fetch, close)

    Hello world
    I have a small doubt about when to use the cursor for loop and when to use the cursor for loop and the cursor (open, fetch, close).
    Well, I'm not the difference between implicit and explicit cursor. So please tell me how I got to know, what to use and when?




    Kind regards
    BS2012

    Published by: BS2012 on January 29, 2013 12:15

    All SQLs are analyzed, stored and executed as cursors. Thus, you will always use a cursor.

    The problem is that languages, such as PL/SQL, provide different interfaces to interact with the SQL cursor. As the ref, the slider interface, the interface DBMS_SQL slider interface and so on.

    Each of these interfaces offers different features. For example, using the interface DBMS_SQL allows binding dynamics and dynamic recovery. The Ref Cursor interface allows your code PL/SQL pass a handle to a reference pointing to the SQL cursor, to an external client. Etc.

    The fundamental reason for the use of an explicit cursor interface is mainly that you own and manage bulk made extraction output provided by PL/SQL cursor.

    With a cursor FOR , the motor loop of PL/SQL optimize the loop by extracting block a 100 lines both. However, you cannot access this collection in bulk directly inside the loop.

    With an explicit cursor interface, you specify the size of the extraction in bulk via the clause LIMIT , and you set the variable of collection to use. This allows you to use the collection directly variable inside the loop.

    However, the need to do - code manually in bulk collection - rarely occur in the daily programs in PL/SQL. A line of treatment is both slow and not well fits. And even if your bulk code collects lines, these lines must still be processed one at a time in your code. It is much more efficient and scalable rather write SQL code, and make the engine SQL the line of treatment for you.

  • The execution of a stored procedure from inside the cursor for loop?

    I posted this in the SQL Developer forum, but I tried in SQLPlus and get the same error, so I think it's an encoding issue.
    I have a piece of code that I'm trying to write that will only be executed once. The goal: we have three tables relating to the pieces of information. Each table has a column that stores the number of site that belongs to the part. We want to copy the parts of a site to about 130 sites which don't have any info on parts. The number of site is stored in another table. So I created three stored procedures, one for each of the three tables that we, who take 2 inputs: a source and destination site. Procedure names are: ptfile_copy_fac, ptxref_copy_fac and ptvndrs_copy_fac.

    The problem I have is that I can run the procedures in a separate worksheet in SQL Developer, but when they are integrated in this cursor for loop, I get the following message from SQL Developer:

    ORA-06550: line 23, column 11:
    PLS-00103: encountered the symbol "PTFILE_COPY_FAC" during the expected in the following way:
    := . (@ %; immediate)
    The symbol ': = ' was replaced by 'PTFILE_COPY_FAC' continue.

    He repeated this for each of the three methods. I have attached the code I am trying to run below. He expects an assignment operator, but I have no idea why.

    If there is a better way to do this, by all means let me know. I'm a SQL Server guy, I'm not sure how to do what I do using PL\SQL.

    / * Declares the variables source_fac and dest_fac.
    The source_fac is the installation that we copy parts.
    The dest_fac is the installation we copy parts to.* /

    DECLARE
    source_fac facility.facility_num%type;
    INSTALLATION OF DEST_FAC. TYPE % FACILITY_NUM;

    / * Declare cursor to use loop for.
    Slider load number installation and the status of the installation.
    Is not installation of 1 or 2, since these will be
    the main source of facilities.*.

    CURSOR fac_cursor
    IS
    SELECT
    facility_num,
    div_state
    Of
    installation
    WHERE
    facility_num NOT IN (1,2);
    BEGIN
    FOR fac_row IN fac_cursor
    LOOP

    / * Test for the State of the installation. If a Canadian State, the source_fac value 2.
    Otherwise, the value source_fac 1.* installation.

    IF fac_row.div_state IN ("AB", "BC", "Mo", "NB", "NL", "NT", "NS", "NAKED", "WE", "PE",
    "QC", "SK", "YT")
    THEN
    source_fac: = 2;
    ON THE OTHER
    source_fac: = 1;
    END IF;

    / * Sets the installation of destination to the facility_num from the cursor * /.

    DEST_FAC: = FAC_ROW. FACILITY_NUM;

    / * Execute the three procedures, past of the source and dest AEC variable * /.

    run ptfile_copy_fac (source_fac, dest_fac);
    run ptxref_copy_fac (source_fac, dest_fac);
    run ptvndrs_copy_fac (source_fac, dest_fac);

    END LOOP;

    END;

    Published by: SunDevilKid on March 3, 2010 15:31
    Update the comments you make more sense of the code.

    EXECUTE is a SQLPlus command, change your code to

    dest_fac := fac_row.facility_num;
    ptfile_copy_fac(source_fac, dest_fac);
    ptxref_copy_fac(source_fac, dest_fac);
    ptvndrs_copy_fac(source_fac, dest_fac);
    END LOOP;
    

    Max
    http://oracleitalia.WordPress.com

  • Cursor for loop

    Hey Experts,.

    Can we consider cursor for loop as an example of cursor name

    as

    CREATE or REPLACE function TotalIncome (name_in IN varchar2) RETURN varchar2 IS total_val number (6);   cursor c1 is SELECT monthly_income FROM Employees WHERE name = name_in; BEGIN total_val: = 0;   FOR employee_rec in c1 LOOP total_val: = total_val + employee_rec.monthly_income;   END LOOP;   RETURN total_val; END; In this example, we have created

    SShubhangi wrote:

    Can we consider cursor for loop as an example of cursor name

    Laughing out loud

    Your code example explicitly sets a CURSOR variable in the PL/SQL block. Implied things happening opens, fetch and closing the cursor. But that the cursor is declared (in the DECLARE section), it's an explicit cursor - like the whole code block now has a way explicit to reference this slider.

    An approach of implicit cursor would be as follows:

    begin
      for c in(select col1, col2 from table1) loop
        .. do something..
      end loop;
    end;
    

    As you can see - there is no declaration of a cursor variable. A reference implementation is created instead and are accessible only within the construction that creates this reference - that is FOR loop in this case. The rest of the BEGIN... END block cannot refer to this cursor.

    Do not forget the advice of other posters however. In PL/SQL cursor loops is often the WRONG approach to the treatment of data - as it deals with processing (using the PL/SQL) line and not much treatment faster and scalable set of data using SQL only.

  • PLSQL cursor for loop - no_data_found exception

    Hi all

    Please, could you help me. I start to learn PL/SQL, so please be pattient.

    the very simple block. Base table emp (for Oracle), he sucks with more then 5000 large salary. I thought that the result would be "aaa", but result is actually empty.

    declare
      cursor c1 (v_num number) is
        select ename,sal
        from emp
        where sal > v_num;
    begin
      for rec in c1(5000) LOOP
        begin
        dbms_output.put_line('Employee: ' || rec.ename || ' has a salary of ' || rec.sal);
      exception
      WHEN NO_DATA_FOUND THEN
        dbms_output.put_line('aaa ');
      end;
      END LOOP ;
    end;
    /
    
    

    How can I solve this problem?

    Thank you much for the help.

    With the help of a cursor for loop will never throw an exception no_data_found.

    Despite everything, you try to catch all exceptions thrown by dbms_output.

  • Cursor for loop in PlSql

    while I was studying on cursor for loop I found this statement in the web

    "A cursor FOR loop implicitly declares its index of the loop as the % ROWTYPE record."

    for example an emp table contain more columns empno, ename, sal, hiredate deptno

    and take a cursor for loop until

    for rec in select empno, sal from emp loop

    If the cursor loop for said index of the loop as a % rowtype our cursor statement must include all columns and follow the data type compatabulity.

    Here our cursor statement includes only a few columns, if we use % rowtype to select all columns but here we do not have it.

    Please can someone explain what is happening in the cursor for loop?

    Type % line is not for the table. its for the cursor.

    its almost like cursor % rowtype

    Select ename, sal from emp will be rowtype of ename and sal... not all the columns EMP

  • declareing cursor for loop inside another cursor for loop

    Hi friends,

    Is it possible declareing cursor loop within another cursor for loop for.

    Please guide for example?

    You can even declare cursor within the cursor loop

    declare
    cursor c1 is select deptno from the Department;
    BEGIN
    for cr1 in c1
    loop
    declare
    cursor c2 is select ename from emp where deptno = cr1.deptno;
    Start
    for cr2 in c2
    loop
    dbms_output.put_line (CR1. DEPTNO | ' ' || CR2.ename);
    end loop;
    end;
    end loop;
    end;

  • CURSOR for loops or an associative array

    I just want to know the advantages and disadvantages of the CURSOR for loops. As a general rule, what guys do you prefer: associative array with CURSOR for loops?


    If you use the CURSOR for loop, is it not difficult to debug?

    PL/SQL Developer, I do not see what values are stored in the CURSOR for loop (in SP master_proc below) as
    There are no variables to watch. Not sure if the TOAD can show these values

    If I had used an associative array (master_proc2 below), I can see the values stored in the table by clicking on "show Collection"variable in PL/SQL developer.




    create table emp2 as select * from emp;
    
    
    create or replace procedure my_proc(p_empno in number)
    as
    begin
    update emp2 set sal=sal+100 where empno=p_empno;
    end;
    /
    
    --Using CURSOR FOR loop
    
    create or replace procedure master_proc
    as
    begin
         for rec in (select empno from emp2 where empno>7700)
         loop
              my_proc (rec.empno);
         end loop;
    end;
    /
    
    -- Using Associative arrays
    create or replace procedure master_proc2
    as
    type v_empno_type is table of number index by pls_integer;
    v_empno v_empno_type;
    
    begin
    select empno bulk collect into v_empno from emp2 where empno>7700;
    
    for i in 1..v_empno.count
     loop
        my_proc (v_empno(i));
     end loop;
    end;
    /

    VitaminD wrote:
    Thank you Tubby. If you are faced with a situation where you MUST use a loop. Then you would go to associative arrays rather than CURSOR FOR loops. Right?

    Doesn't happen too often, but if/when then I would do as I said in my first post. Use the transformation, the collection table in BULK and FORALLs.

    If we use your example posted, I would NOT spend a single table (in a loop mode) value I would be transmitted in the OVERALL picture and treat it with FORALL.

    So, I would still use neither of the approaches that you mentioned.

  • Cursor object and cursor for loop back

    I am beginner in Oracle and the serious database of programming in general. Right now I'm studying the sliders. I more or less understand how works when the cursor returns a record, but I can't understand why this does not work when the cursor return object and I use "cursor for loop.

    Here's the test code:

    CREATE or REPLACE TYPE typ_Test () AS OBJECT
    text VARCHAR2 (50)
    );

    CREATE TABLE t_Test to typ_Test;

    INSERT INTO t_Test VALUES (typ_Test('111'));
    INSERT INTO t_Test VALUES (typ_Test('222'));

    -work, simple loop
    DECLARE
    CURSOR cur IS SELECT VALUE (o) FROM t_Test o;
    typ_Test obj;
    BEGIN
    Heart OPEN;
    LOOP
    Fetch cur INTO obj;
    OUTPUT WHEN heart % NOTFOUND;
    dbms_output.put_line (obj. (Text);
    END LOOP;
    CLOSE cur;
    END;



    -doesn't work, cursor for loop
    DECLARE
    CURSOR cur IS SELECT VALUE (o) FROM t_Test o;
    BEGIN
    FOR news of obj IN LOOP
    dbms_output.put_line (obj. (Text);
    END LOOP;
    END;



    Error report:
    ORA-06550: line 5, column 30:
    PLS-00302: 'TEXT' element must be declared.
    ORA-06550: line 5, column 5:
    PL/SQL: Statement ignored
    06550 00000 - "line %s, column % s:\n%s".
    * Cause: Usually a PL/SQL compilation error.


    EDIT:
    In fact I found no examples on the net of its use "cursor for loop" with cursor that returns the object. Only when the record is returned...

    Published by: user10393567 on February 10, 2009 07:38

    user10393567 wrote:
    Now, in the 'loop' example for what looks "obj" is a folder, not an object, and 'x' is attribute of this recording... But the cursor must return an object, not a record... What Miss me?

    In the FOR loop "obj" is a pointer to the cursor/query, not a subject in its own right. It gives you just a reference in the query.

    So with that you are referring to the query, but then you need to refer to the column in the query that you are interested, so why there need a name (in my case I called it 'x'). 'x' is the object, and then you refer to the attribute of this object "text".

    In the first request that you simply select the value directly object in a variable, so no matter what it's called in the query values are returned by the position that is the first column in the query goes into the first variable in the INTO clause. Once you have that then the variable itself contains the object, and you can just refer to the attribute within that.

    Hope that makes sense.

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

    Hi friends,

    I run the code below and clocked at the same time for each line of code using DBMS_PROFILER.
    CREATE OR REPLACE PROCEDURE TEST
    AS
       p_file_id              NUMBER                                   := 151;
       v_shipper_ind          ah_item.shipper_ind%TYPE;
       v_sales_reserve_ind    ah_item.special_sales_reserve_ind%TYPE;
       v_location_indicator   ah_item.exe_location_ind%TYPE;
    
       CURSOR activity_c
       IS
          SELECT *
            FROM ah_activity_internal
           WHERE status_id = 30
             AND file_id = p_file_id;
    BEGIN
       DBMS_PROFILER.start_profiler ('TEST');
    
       FOR rec IN activity_c
       LOOP
          SELECT DISTINCT shipper_ind, special_sales_reserve_ind, exe_location_ind
                     INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
                     FROM ah_item --464000 rows in this table
                    WHERE item_id_edw IN (
                             SELECT item_id_edw
                               FROM ah_item_xref --700000 rows in this table
                              WHERE item_code_cust = rec.item_code_cust
                                AND facility_num IN (
                                       SELECT facility_code
                                         FROM ah_chain_div_facility --17 rows in this table
                                        WHERE chain_id = ah_internal_data_pkg.get_chain_id (p_file_id)
                                          AND div_id = (SELECT div_id
                                                          FROM ah_div --8 rows in this table 
                                                         WHERE division = rec.division)));
       END LOOP;
    
       DBMS_PROFILER.stop_profiler;
    EXCEPTION
       WHEN NO_DATA_FOUND
       THEN
          NULL;
       WHEN TOO_MANY_ROWS
       THEN
          NULL;
    END TEST;
    The SELECT inside the LOOP FOR cursor query took 773 seconds.
    I tried to use COLLECT in BULK instead of a cursor for loop, but it did not help.
    When I took the select query separately and executed with a value of the sample, and then he gave the results in a Flash of a second.

    All tables have primary key index.
    Any ideas what can be done to make this code more efficient?

    Thank you
    Raj.
    DECLARE
      v_chain_id ah_chain_div_facility.chain_id%TYPE := ah_internal_data_pkg.get_chain_id (p_file_id);
    
      CURSOR cur_loop IS
      SELECT * -- better off explicitly specifying columns
      FROM ah_activity_internal aai,
      (SELECT DISTINCT aix.item_code_cust, ad.division, ai.shipper_ind, ai.special_sales_reserve_ind, ai.exe_location_ind
         INTO v_shipper_ind, v_sales_reserve_ind, v_location_indicator
         FROM ah_item ai, ah_item_xref aix, ah_chain_div_facility acdf, ah_div ad
        WHERE ai.item_id_edw = aix.item_id_edw
          AND aix.facility_num = acdf.facility_code
          AND acdf.chain_id = v_chain_id
          AND acdf.div_id = ad.div_id) d
      WHERE aai.status_id = 30
        AND aai.file_id = p_file_id
        AND d.item_code_cust = aai.item_code_cust
        AND d.division = aai.division;         
    
    BEGIN
      FOR rec IN cur_loop LOOP
        ... DO your stuff ...
      END LOOP;
    END;  
    

    Published by: Dave hemming on December 4, 2008 09:17

  • Question about support for LabVIEW DLLS and Unicode

    Hello

    I have a question about LabVIEW and DLL functions calls.

    I use a DLL (sorry, I can't share it) that was written in C. It was written to support Unicode and non-Unicode function calls.

    The Unicode function is valid, then FunctionNameW is called if FunctionNameA is called.

    I am building a few VI to access the library. I have the regular functions of FunctionNameA work.

    My question is, does LabVIEW support versions of function FunctionNameW Unicode, and if so is it necessary Although LabVIEW is already working with the standard function call?

    Am I being redundant or what should I build in Unicode support?

    The first time I tried to test the Unicode functions, I had an error, and I guess this is a system setting.

    Thank you for your time in advance.

    DB_IQ wrote:

    I don't think I have TO implement the Unicode, but I want if I can.

    For what I do, I think almost it is not serious. But I wanted to know if it could be used.

    The short answer is "Yes, you can do it."  However, it may open a new Pandora's box.  If you're not careful, problems and complications that can still spread to other projects that are not using Unicode!  It is better not to summon this monster unless there is absolutely no other way to do the job.

  • Question about encryption for a VPN established between two of our sites

    We have two routers Cisco 2951, one at our main location and one at a branch.  An engineer for a local company came and worked all the parameters, including the VPN between the two men.

    For an upcoming exam, the firm wanted to know what kind of security/encryption has been implemented between the two routers.  The engineer is no longer available, so I've went over our configuration files for each of the routers and will have questions about what to tell them (I'll be the first to admit that some of this stuff is over my head).

    I enclose the portions of the configs with "crypto" information he put in place.  If you see something wrong, or need something extra, let me know.

    Thanks in advance!

    That's what you use:

    Phase 1: 3DES, SHA1, PSK, Group2 DH (1024 bits), life time 86400 s

    Phase2: 3DES, SHA1

    Which is today considered legacy crypto, but probably nothing to worry. The crypto-config has always considered that there is "room for improvement"...

  • cursor for loops with exception handling

    Hi all

    I use oracle11g I need to write a stored procedure to about 10 select statements with the managements of exceptions for each select statement. I am unable to handle the exception handling.please guys help

    Here is the code sample I wrote

    CREATE OR REPLACE PROCEDURE TEST_PROC

    (P_ID IN VARCHAR2,

    P_MOB IN VARCHAR2,

    P_OUT_MSG OUT VARCHAR2)

    AS

    CURSOR CUR_RES AS SELECT NAME, INFO, VER_DETAILS FROM TABLE_NAME WHERE ID = P_ID AND MOBILE_NO IS P_MOB;.

    BEGIN

    FOR REC IN CUR_RES LOOP

    P_OUT_MSG: = 'BKY000. '

    END LOOP;

    EXCEPTION

    WHEN NO_DATA_FOUND THEN

    P_OUT_MSG: = 'BKY001. '

    END;

    OUTPUT DESIREE WHILE RUNNING IN A JAVA APPLICATION IS REQUIRED

    IF THE DATA FOUND BKY000 | RESULT OF THE SELECT STATEMENT

    IF DATA NOT FOUND BKY001

    PLEASE HELP WITH SAMPLE... PLEASE FRIENDS

    It's more clear now

    create or replace procedure test_proc (p_id in varchar2, )

    p_mob in varchar2,

    p_out_msg out varchar2,.

    p_result on sys_refcursor

    ) as

    v_err_msg varchar2 (300);

    row_count number;

    no_data_returned exception;

    nonunique_column exception;

    Start

    Open Select p_result *.

    WCP

    where deptno = to_number (p_id)

    and job = p_mob;

    Select count (*)

    in row_count

    WCP

    where deptno = to_number (p_id)

    and job = p_mob;

         

    If row_count = 0 then

    raise no_data_returned;

    end if;

    Select keep max (count (*)) (dense_rank first order by Count)

    in row_count

    from (select *)

    WCP

    Union all - simulating a duplicate line

    Select 7839, "ETBIN', 'PRESIDENT', null, trunc (sysdate), 3000, null, 10

    of the double

    )

    where deptno = to_number (p_id)

    and job = p_mob

    Group by empno

    view count (*) > 1;

    If row_count > 1 then

    raise nonunique_column;

    end if;

    p_out_msg: = 'BYK0000 ';

                       

    exception

    When no_data_returned

    then p_out_msg: = "BYK001";

    When nonunique_column

    then p_out_msg: = "BYK002";

    while others

    then v_err_msg: = ' procedure TEST_PROC: error: ' | SQLCODE. ': ' || substr (SQLERRM, 1, 200);

    raise_application_error(-20000,v_err_msg);

    end;

    declare

    R_C sys_refcursor;

    E_r emp % rowtype;

    E_m VARCHAR2 (255);

    DEPTNO number: = 10;

    VARCHAR2 (30) employment: = "PRESIDENT";

    Start

    dbms_output.put_line (' input parameters: deptno = ' | to_char (deptno) |) '; job = ' | Job);

    test_proc (to_char (DEPTNO), Job, E_m, R_C);

    dbms_output.put_line (' result: ' | e_m);

    If e_m = "BYK0000" then

    loop

    extract r_c in e_r;

    When the exit r_c % notfound;

    dbms_output.put_line (to_char (E_r.empno) |' |) '|| RPAD(E_r.Ename,10) |' | '|| RPAD(E_r.job,10) |' | '|| TO_CHAR (E_r.SAL, 'fm99990'));

    end loop;

    end if;

    exception

    While other then dbms_output.put_line ('exception: ' | sqlcode |) ': ' || substr (SQLERRM, 1, 200));

    end;

    input parameters: deptno = 10; job = PRESIDENT

    result: BYK002

    Statement processed.

    Concerning

    Etbin

  • Cursor for loop and IN LOOP

    Hi gurus,

    I'm going to the table like this:

    TEST
    NO      PK
    VALUE
    And I wrote a test cursor procedure to retrieve values such as:
    CREATE OR REPLACE
    PROCEDURE test_proc_cursor
      (
        p_no OUT test.no%TYPE,
        p_value OUT test.value%TYPE)
    AS
      CURSOR proc_cursor
      IS
         SELECT no,value INTO p_no, p_value FROM test;
    BEGIN
      OPEN proc_cursor;
      LOOP
        FETCH proc_cursor INTO p_no, p_value;
        EXIT
      WHEN proc_cursor%NOTFOUND;
        dbms_output.put_line(p_no||'       '|| p_value);
      END LOOP;
      CLOSE proc_cursor;
    END test_proc_cursor;
    But, my question is, I have used the simple LOOP in the cursor. Anyone can write the same logic of cursor with all IN LOOP and LOOP FOR it please

    Thank you

    Published by: user10679113 on January 22, 2009 07:53

    Published by: user10679113 on January 22, 2009 07:54

    Published by: user10679113 on January 22, 2009 07:55

    Hello

    SQL> DECLARE
      2    p_no    test.no%TYPE;
      3    p_value test.value%TYPE;
      4    CURSOR proc_cursor IS SELECT no,value FROM test;
      5  BEGIN
      6    OPEN proc_cursor;
      7    FETCH proc_cursor INTO p_no, p_value;
      8    WHILE proc_cursor%FOUND LOOP
      9      dbms_output.put_line(p_no||'       '|| p_value);
     10      FETCH proc_cursor INTO p_no, p_value;
     11    END LOOP;
     12    CLOSE proc_cursor;
     13  END;
     14  /
    1       awe
    2       JHKBHNJ
    3       548539
    
    PL/SQL procedure successfully completed.
    
    SQL> DECLARE
      2    CURSOR proc_cursor IS SELECT no,value FROM test;
      3  BEGIN
      4    FOR cRec IN proc_cursor LOOP
      5      dbms_output.put_line(cRec.no||'       '|| cRec.value);
      6    END LOOP;
      7  END;
      8  /
    1       awe
    2       JHKBHNJ
    3       548539
    
    PL/SQL procedure successfully completed.
    
    SQL> BEGIN
      2    FOR cRec IN (SELECT no,value FROM test) LOOP
      3      dbms_output.put_line(cRec.no||'       '|| cRec.value);
      4    END LOOP;
      5  END;
      6  /
    1       awe
    2       JHKBHNJ
    3       548539
    
    PL/SQL procedure successfully completed.
    

    Kind regards
    Dima

Maybe you are looking for