Search code examples
for-loopplsqloracle11gconditional-statementsprocedure

pl/sql loop records select oracle plsql


I have a select statement that I am trying to loop over and increment a variable based on the condition of the select statement, then return the variable as an out so I can do something with it in some front end code. I am using oracle 11g and I am seeing a few ways I can do this... but I am not sure which is the best way. I have some of what I am trying to do below, but again stopped because of confusion.

First I am setting my proc and 'in variable'

PROCEDURE SEEKER (pMonkeyID IN Number, vMarkCounter OUT Number)
AS
BEGIN

CURSOR seeker_cur IS
    Select Mokney_approved, Monkey_vaulted 
    from MonkeyBookApps 
    where MonkeyID = pMonkeyID
    and Monkey_doc_type = 'BANANA' 
    order by docu_approv_timestamp,monkey_doc_type,monkey_doc_approved desc

OPEN seeker_cur;

begin

   OPEN Seeker_cur;
   vMarkCounter := 0;

Here is the part I am not sure about. Should I loop and then exit if the condition is not met or should I do an if statement and somehow determine if there is a record that could be greater than one? If so how would that work? Is there a benefit to doing one way over the other? So... I am going to sudo-code what I am trying to do (below):

FOR (however many records) in Seeker_cur
IF seeker_cur (not found) or (returns no records)

EXIT or (break for loop);
ELSE
LOOP

vMarkCounter := vMarkCounter + 1;

EXIT WHEN seeker_cur is out of records (somehow)
END IF;
END LOOP;

END; 
END SEEKER;

I am sure there are a few ways to do this. What ways would you suggest?


Solution

  • why dont you use implicit cursor , it will open and close itself:

    DECLARE
    
    CURSOR seeker_cur IS
        Select Mokney_approved, Monkey_vaulted 
        from MonkeyBookApps 
        where MonkeyID = pMonkeyID
        and Monkey_doc_type = 'BANANA' 
        order by docu_approv_timestamp,monkey_doc_type,monkey_doc_approved desc;
    
      vMarkCounter number:=0;
    
    BEGIN
    
      FOR i IN seeker_cur 
      LOOP
        vMarkCounter := vMarkCounter+1;
      END LOOP;
    
      dbms_output.put_line(vMarkCounter);
    END;