Looping through a cursor (newbie)

I am trying to construct a dynamic insert statement. I am retrieving (using a select) the column names from one of my tables into a cursor. I would now like to loop through the cursor and extract the column names. Is there anyway to loop through the cursor like you can normally do as below:
for i = 0 to cursor%rowcount
tempstring = tempstring + ',' + cursor.i; (something along these lines)
end for
and then do 'insert into tablename (' || tempstring
Am I making sense?

There are several methods to process cursors and you can easily find them
here.
http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96624/01_oview.htm#740
http://download-west.oracle.com/docs/cd/B10501_01/appdev.920/a96624/06_ora.htm#36656
And before trying to use dynamic sql it would be better to think would you really
need it...
Rgds.

Similar Messages

  • How to loop through SYS_REF cursor records

    Hello, I'm using the following oracle version
    PL/SQL Release 11.2.0.2.0 - Production
    I'd like to create an Oracle anonymous block which calls another procedureB. ProcedureB returns the result of a query in the form of a SYS_REF cursor. Once the result is returned into the anonymous block, I'd like to loop through specific columns of the result set. I've started with this, but it isn't right. Could you please let me know what I'm doing wrongly?
    create or replace procedure procedureRFHA(numIn IN number, cursorOUT OUT sys_refcursor) as
    begin
    open cursorOUT for
    select 'A' col1, 'B' col2
    from dual
    where 3 = numIn
    union all
    select 'C' col1, 'D' col2
    from dual
    where 3 = numIn;
    end;
    declare
    TYPE r_type IS RECORD (
    col1 VARCHAR2 (1),
    col2 VARCHAR2 (1)
    returnCursor sys_refcursor;
    begin
    procedureRFHA(3, returnCursor);
    LOOP
    FETCH returnCursor INTO r_type;
    dbms_output.put_line(r_type.col1);
    EXIT WHEN returnCursor%NOTFOUND;
    END LOOP;
    CLOSE returnCursor;
    end;

    Then please mark the question ANSWERED.

  • Navigating through a cursor

    Hi folks,
    Lets say I have a cursor and I am passing a Purchase Order number and it returns a purchase order with 100 items.  Now I use FOR function to step through those 100 items in the cursor.  Now lets suppose I have a legitimate reason to jump immediately to the 90th item in the list.  Rather than step through the FOR / END FOR loop 90 times is there any way to automatically jump to the 90th item?  My guess from what I've read in documentation is NO but I thought I would ask anyway.
    Thanks,
    -Patrick

    Hi Patrick,
    One other possible approach given your current logic would be to index into a result set, say at position 90, by doing SELECT .. FROM .. WHERE .. OFFSET 90 (and if needed, LIMIT if you need a subset).
    Hard to say what the performance impact would be, but generally speaking looping with single selects carries more overhead than looping through a cursor. But perhaps it's a useful approach?
    Regarding your logic, it may be too much trouble - but if not, I'd be interested to hear what all is required.
    If you have to look for a certain count, could you not do something like:
    SELECT "JOIN_FIELDS", COUNT(*).. FROM.. GROUP BY.. HAVING COUNT(*) > 5 (as example)
    and then join those results?
    I've seen a lot of creative ways to solve complex logic with set-processing approaches. Perhaps there's more room for optimization and simplification?

  • Can the return from xsql:ref-cursor-function be saved & looped through XSQL?

    If <xsql:ref-cursor-function> returns one field for a number of rows, is there a way to save those values and loop through the data retrieved for other query process within XSQL? Any example?
    Thanks.
    null

    You have a couple of options.
    You can process the XML returned by <Xsql:ref-cursor-function> as the normal part of XSLT processing, or you can write a custom action handler that aggregates the action handler for <xsql:ref-cursor-function> and then uses DOM to operate on the return value.
    Search the Online XSQL Pages Documentation for the term "MyIncludeXSQLHandler" for some sample code that illustrates building a customer action handler that aggregates one of the built-in handlers.

  • Pass REF CURSOR to Procedure and LOOP through it

    Hi All,
    I am trying to figure out how I can pass a ref cursor to a procedure and then loop through it. I have provided an example of what I am attempting to do...just not really sure how to open the ref cursor when it is passed ot the sproc and iterate through it?
    Any info would be greatly appreciated.
    Version:
    Oracle Database 10g Enterprise Edition Release 10.2.0.3.0 - 64bi
    PL/SQL Release 10.2.0.3.0 - Production
    CORE     10.2.0.3.0     Production
    TNS for Linux: Version 10.2.0.3.0 - Production
    NLSRTL Version 10.2.0.3.0 - Production
    Create Or Replace Package test_ref_pkg
    AS
    function get_ref_curs
    RETURN SYS_REFCURSOR;
    procedure process_ref_curs(
    p_ref_cursor        IN  SYS_REFCURSOR
    END test_ref_pkg;
    Create Or Replace Package Body test_ref_pkg
    AS
    function get_ref_curs
        RETURN SYS_REFCURSOR
    IS
        l_ref_curs      SYS_REFCURSOR;
    BEGIN
        OPEN l_ref_curs FOR
        Select 1 ID, 'Test 1' Name
        From DUAL
        UNION ALL
        Select 2 ID, 'Test 2' Name
        From DUAL;
    END get_ref_curs;
    procedure process_ref_curs(
    p_ref_cursor        IN  SYS_REFCURSOR
    IS
    BEGIN
        ---NOT SURE WHAT TO DO TO ITERATE THROUGH THE REF CURSOR I AM PASSING INTO THIS SPROC?----
    END process_ref_curs;
    END test_ref_pkg;Thanks,
    S
    Edited by: ScarpacciOne on May 28, 2010 9:11 AM

    ---NOT SURE WHAT TO DO TO ITERATE THROUGH THE REF CURSOR I AM PASSING INTO THIS SPROC?----
    -- MAYBE I AM SIMPLE, BUT HOW ABOUT FETCH???
    -- if you start to yell, I will yell too!!!!
    Sybrand Bakker
    Senior Oracle DBA

  • Loop through select and create cursor

    Is it possible to create a cursor after looping through a select?
          FOR TEST IN
            SELECT *
              FROM SOMETABLE
             WHERE SOMEID > 100
           ) LOOP
              IF TEST.NAME = 'AB' THEN
                   --CREATE CURSOR AND LOAD DATA
                   --LOAD TEST.ID, TEST.NAME, TEST.ADATE INTO NEW CURSOR
              END IF;
           END LOOP;     This is just a sample not the actual scenario.

    SeshuGiri wrote:
    Is it possible to create a cursor after looping through a select?Yes. But is also usually the wrong thing to do.
    A cursor loop within another cursor loop is known as a nested loop join in SQL. The SQL language is perfectly able to do joins like that. And far better and faster. It has a very clever optimiser and has more sophisticated algorithms than just a nested loop, for joining data sets.
    The sample code you've posted shows a very old 80's style Cobol approach to processing ISAM files or magnetic tape. In a row-by-row fashion.
    This approach does not scale in the modern database, where the SQL language is a data set processing language - and not an I/O interface for merely reading a record/row and writing a record/row as we did in the 80's with file-based data records.
    The basic approach to Oracle is: Maximise SQL. Minimise PL/SQL (Java/etc).
    This means using the very flexible, incredibly powerful, SQL language first and foremost to crunch database data. And only when the processing is beyond the capability of the SQL language alone, employ PL/SQL. Else restrict PL/SQL to managing only the process flow and error handling of SQL language statements.

  • How do I loop through tables, not columns in a table?

    Sorry if this is a long one. My problem is actually quite simple. I am trying to write either an ad hoc PL/SQL block or a stored procedure to loop 18 times (thru 18 tables) and perform a SQL query on those tables, returning 18 resultsets. I would like the results to show up on the screen (or in a spool file, whatever).
    So far I have tried 3 different approaches, none of which have worked.
    1. I tried to assign the select query to a variable (qry) and use EXECUTE IMMEDIATE qry. This forced me thru a variety of errors to declare variables and assign the result to them--EXECUTE IMMEDIATE qry into nm0, nm1, nm2...
    The problem with that was the resultset returned more than the variable was built for as there might be no rows returned, or it might be a thousand rows of data. So I tried changing the variables to VARRAYS, but it gave me a type mismatch as the underlying columns were NUMBER and VARCHAR2.
    DECLARE
         ctr number;
         TYPE NUMLIST IS VARRAY (1000) OF NUMBER;
         TYPE VARLIST IS VARRAY (1000) OF VARCHAR2(15);
         nm0 NUMLIST NOT NULL DEFAULT 1;
         nm1 VARLIST;
         nm2 NUMLIST NOT NULL DEFAULT 1;
         nm3 VARLIST;
         nm17 NUMLIST NOT NULL DEFAULT 1;
         qry VARCHAR2(2000) := 'klx_uln_p000_cells';
    BEGIN
    FOR ctr IN 1..17 LOOP
         IF ctr &lt; 10 THEN
              qry := 'SELECT
              A.DIM_0_INDEX,
              S0.SYM_NAME,
              A.DIM_1_INDEX,
              S1.SYM_NAME,
              A.DIM_2_INDEX,
              S2.SYM_NAME,
              A.DIM_3_INDEX,
              S3.SYM_NAME,
              A.NUMERIC_VALUE,
              B.NUMERIC_VALUE
              FROM
              KHALIX.klx_uln_p00'||ctr||'_cells A,
              KHALIX.klx_ucn_p00'||ctr||'_cells B,
              KHALIX.KLX_MASTER_SYMBOL S0,
              KHALIX.KLX_MASTER_SYMBOL S1,
              KHALIX.KLX_MASTER_SYMBOL S7
              WHERE
              A.DIM_0_INDEX=B.DIM_0_INDEX AND
              A.DIM_1_INDEX=B.DIM_1_INDEX AND...
              A.DIM_7_INDEX=S7.SYM_INDEX';
         ELSE
              qry := 'SELECT
              A.DIM_0_INDEX...
              A.DIM_7_INDEX=S7.SYM_INDEX';
         END IF;
         BEGIN
         dbms_output.put_line('SELECT FOR KLX_ULN_P00'||ctr||'_CELLS');
         dbms_output.put_line(nm16);
         dbms_output.put_line(nm17);
         EXECUTE IMMEDIATE qry into nm0,nm1,nm2,nm3,nm4,nm5,nm6,nm7,nm8,nm9,nm10,nm11,nm12,nm13,nm14,nm15,nm16,nm17;
    --     dbms_output.put_line(qry);
         dbms_output.put_line(nm16);
         dbms_output.put_line(nm17);
         EXCEPTION
              WHEN NO_DATA_FOUND THEN
                   dbms_output.put_line('No data found for Query '||ctr);
         END;
    END LOOP;
    EXCEPTION
         WHEN NO_DATA_FOUND THEN
              dbms_output.put_line('No data found for Query '||ctr);
    END;
    2. So then I used REF CURSOR to create a stored procedure and return the values. That allowed me to run my query AND tokenize the tablenames with a counter so that it would loop through the different tables! However, I still could not get it to display the results without going to SQL Plus and typing 'print c;'.
    3. So, finally I tried to create a looping wrapper around the ref cursor to have some variable (ctr) increment so my query would get performed on table0_cells through table17_cells. This, too, did not work.
    If I manually go to SQL Plus and type:
    variable ctr number
    begin
    :ctr := 1;
    end;
    exec dupe_find(1,:c);
    it will execute for the first table (klx_uln_p001_cells) and I can then type 'print c' to see what was returned. But when I try putting this within a wrapper PL/SQL block with a Loop to make ctr go from 0 - 17 (to loop through table_names klx_uln_p000_cells to klx_uln_p017_cells), it does not work.
    Help! It should be very simple to loop through tables, shouldn't it? I just want a script that will loop through tables, perform a query on each table and display the results. For some reason, I can only find documentation examples on looping through columns that are all in the same table.
    Dave

    Here's a working example using your first strategy ...
    create table t1 (id number);
    create table t2 (id number);
    insert into t1 values (100);
    insert into t1 values (101);
    insert into t2 values (200);
    insert into t2 values (201);
    declare
    v_table_name user_tables.table_name%type;
    type ttab_id is table of t1.id%type index by binary_integer;
    tab_id ttab_id;
    begin
    for i in 1 .. 2 loop
    v_table_name := 't' || i;
    execute immediate 'select id from ' || v_table_name
    bulk collect into tab_id;
    dbms_output.put_line('query from ' || v_table_name);
    for j in 1 .. tab_id.count loop
    dbms_output.put_line(tab_id(j));
    end loop;
    end loop;
    end;
    There are many other ways to do this (especially if you need to do more than just print out the data).
    Richard

  • How to add results of Loop into a Cursor

    Hi,
    I am opening a cursor and looping through each row (it has a select query that queries based on the value of a column obtained from another cursor).
    How can I add all the rows to a new cursor (along with the column value I am getting from the first cursor), as I want to return that to a java program.
    Can I create a new cursor and add the final data to it (that contains all rows), if yes How do I do that?
    Thanks,
    Rommel.
    Message was edited by:
    rommelsharma

    Trying to add data from one cursor to another cursor shows a basic misconception on your part of what a cursor is.
    First, what a cursor is not - it is not a result set. An in-memory set of rowids or results for a SQL. With 1000's of cursors on a database, how would this scale when every cursor needs space for storing its results?
    A cursor is a SQL program - a set of instructions (as per the SQL's execution plan) of how to get the results for that SQL. When a cursor fetch is performed, this program returns the next set of rows from the actual database tables.
    So you cannot take data from one or more cursors and then wrap that into a 3rd cursor.. or more accurately, you should not. The fact that it can be hacked in PL/SQL simply says a lot of the flexibility of PL/SQL.. and not about good sensible use.
    So how then do you "add cursors" together? You do it at SQL level. A cursor is a program. So instead of creating multiple programs, each returning its own results, you make it a single program.
    You combine the SQLs. This means using UNION, JOIN, INTERSECT, etc.
    Solve the problem in SQL first and foremost. That is the most powerful language to use to crunch database data. Do not make the major and fatal performance mistake of treating SQL as a simplistic I/O library for merely reading and writing records.

  • Loop through tables based on data dict values

    Hi,
    I working on an old v7.3.4 database that I'm not familiar with and I want to loop through the tables and count the occurrence of a field value based on table names i've retrieved from the data dictionary. None of the tables have relational keys defined.
    In a cursor I can loop thru all_tab_columns and load variables with the table, column names, and the datatype, but then I want to use these values in a second nested cursor to loop through each table found by the first cursor.
    When I do :
    Select var_colname from var_tabname
    i get
    The following error has occurred:
    ORA-06550: line 23, column 10:
    PLS-00356: 'V_TABNAME' must name a table to which the user has access
    ORA-06550: line 22, column 5:
    PL/SQL: SQL Statement ignored
    ORA-06550: line 22, column 12:
    PLS-00320: the declaration of the type of this expression is incomplete or malformed
    ORA-06550: line 27, column 7:
    PL/SQL: SQL Statement ignored
    so it would seem I can't use a variable to substitute the table name in the 'from' clause. Does anyone know of a way round this ?
    Thanks in advance

    Hi,
    You will have to use dynamic sql to create your second cursor.
    DECLARE
         v_sql_query VARCHAR2(400);
         TYPE cur_typ IS REF CURSOR;
         c1 cur_typ;
         mYRec MyTable%rowtype;
    BEGIN
         v_sql_query := 'select * from MyTable';
         OPEN c1 FOR v_sql_query;
              LOOP
              FETCH c1 INTO mYRec;
                   EXIT WHEN c1%NOTFOUND;
                   EXIT WHEN c1%NOTFOUND IS NULL;
    /*processing here*/
              END LOOP;
         CLOSE c1;
    END;
    Regards

  • Dbma_scheduler job executing procedure that loops through all client schemas in the database rolls back transaction incase of exception

    Hi,
    Needed your inputs on approach to implement a job using dbms_scheduler.
    We have around 2000 schemas. Each schema has a package with 2 procedures.
    The requirement is to create a single job in SYS that would loop through each schema and run the procedures at a specific time ( once a day) and send email notification on success or failure.
    Job script:
    BEGIN
        dbms_scheduler.create_job( job_name=> 'LOAD_EACH_SCHEMA_AUDIT_DATA',
                                   job_type=>'PLSQL_BLOCK',
                                   job_action=>'BEGIN  sys.p_loadaudit;     
                                    END;',
                                   start_date=>systimestamp,
                                   repeat_interval=>'FREQ=MINUTELY;INTERVAL=1',
                                   number_of_arguments=>0,
                                   enabled=> true,
                                   comments=>'Job repeat interval is every 5 mins' );
                                   END;
    Note: for testing purpose i have set repeat interval to minutely.
    Procedure job will be executing:
    Procedure sys.p_loadaudit:
    CREATE OR REPLACE
    PROCEDURE p_loadaudit
    AS
        v_count          NUMBER:= 0;
        lv_error_message VARCHAR2(4000);
        vstmt            VARCHAR2(4000);
    BEGIN
        FOR i IN
        ( SELECT username FROM dba_users WHERE username LIKE 'ABCFIRM%'
        LOOP
            vstmt:= 'begin ' || i.username || '.pkg_audit_info.p_load_coa; end;';
            EXECUTE immediate vstmt;
            vstmt:= 'begin ' || i.username || '.pkg_audit_info.p_load_am; end;';
            EXECUTE immediate vstmt;
        END LOOP;
    EXCEPTION
    WHEN OTHERS THEN
        lv_error_message := 'Error in procedure p_loadaudit: ' || SQLCODE || ' -ERROR- ' || SUBSTR(
        sqlerrm,1,300) || '*' || dbms_utility.format_error_backtrace;
        raise_application_error(-20002,lv_error_message);
    END p_loadaudit;
    Example of one schema: SCHEMA_01
    create or replace
    PACKAGE pkg_audit_info
    AS
    type cursortype
    IS
        ref
        CURSOR;
            PROCEDURE p_load_COA;
            PROCEDURE p_load_AM;
       END pkg_audit_info;
    create or replace
    PACKAGE body pkg_audit_info
    AS
    PROCEDURE p_load_COA
    AS
    BEGIN
    INSERT INTO TABLE1();
    EXCEPTION
    WHEN OTHERS THEN
        lv_error_message := 'Error in procedure pkg_audit_info.p_load_COA: ' || SQLCODE
        || ' -ERROR- ' || SUBSTR(SQLERRM,1,300) || '*' || dbms_utility.format_error_backtrace;
        RAISE_application_error(-20002,lv_error_message);
    END p_load_COA;
    PROCEDURE p_load_AM
    AS
    BEGIN
    INSERT INTO TABLE2();
    EXCEPTION
    WHEN OTHERS THEN
        lv_error_message := 'Error in procedure pkg_audit_info.p_load_AM: ' || SQLCODE ||
        ' -ERROR- ' || SUBSTR(SQLERRM,1,300) || '*' || dbms_utility.format_error_backtrace;
        RAISE_application_error(-20002,lv_error_message);
    END p_load_AM;
    END pkg_audit_info;
    Table1 and table1 exist in schema_01.
    All 2000 schemas have same package.procedures.
    Due to security reasons i have removed the actual code.
    I was able to execute the job successfully. However, when a schema procedure (SCHEMA_01.pkg_audit_info.p_load_COA) throws an exception, the job fails and all transaction is rolled back.
    Is there a way to loop through each schema and execute the related procedures. Even if exception happens, it should rollback only for that schema and continue the other schemas in the loop?
    Please let me know if there is a better way to achieve this. Is the way i am handling exceptions in the job/procedure correct?
    Thanks

    Hi,
    RAISE_APPLICATION_ERROR will cause the program to exit back to the caller, even if you place it in a block within the loop, so the RAISE or RAISE_APPLICATION_ERROR instruction should be placed in your "pkg_audit_info.p_load_AM" and "pkg_audit_info.p_load_coa" procedures. This way, you can use a block inside the loop and log the error.
    FOR i IN
        ( SELECT username FROM dba_users WHERE username LIKE 'ABCFIRM%'
        LOOP
           BEGIN
            vstmt:= 'begin ' || i.username || '.pkg_audit_info.p_load_coa; end;';
            EXECUTE immediate vstmt;
            vstmt:= 'begin ' || i.username || '.pkg_audit_info.p_load_am; end;';
            EXECUTE immediate vstmt;
    EXCEPTION
    WHEN OTHERS THEN  
        --> Log the error in a custom log table otherwise you will not know what happened for that schema: don't forget the username
    END;
    END LOOP;

  • How to loop through a single row of data?

    What I'm trying to do is use a cursor to loop through a clob. When I create my cursor I get the an error telling me that the table does not exist. Which implies that I have an implicit cursor. Is there a way to get around this?

    > How to loop through a single row of data?
    By not looping as there is only a single row?
    > What I'm trying to do is use a cursor to loop through a clob
    Processing (looping through) a CLOB has nothing to do with a cursor.
    > When I create my cursor I get the an error telling me that the table does
    not exist. Which implies that I have an implicit cursor.
    Incorrect. It simply means that
    a) you do not have permissions to access that table from within the current context
    b) it does not exist (e.g. you have misspelled the object name, you have not qualified it properly within the current scope, etc)

  • How to loop through columns of a table?

    Hi, guys
    Is there a way to loop through each column of a table? If there is a way, then how?
    I have a table with columns of different datatypes , and I want to set default values for each column with a loop but don't know how to make it happen.
    For example,
    Table: Employees
    declare
      rec  Employees%ROWTYPE;
    begin
      for col in rec.empno .. rec.location loop
         if col = rec.empno then -- set default value for column empno;
      end loop;
    end;
    /Sorry, I am a newbie to PL/SQL. Please help!
    Thanks in advance.
    Edited by: HappyJay on 2010/05/11 10:36

    Hi,
    You can query the data dictionary views all_tab_columns (or user_tab_columns) to get the names of all the columns in a particular table.
    Here's an easy way (but not a very efficient way) to loop through them:
    SET     SERVEROUTPUT     ON
    BEGIN
         FOR  c IN ( SELECT  column_name
                         FROM    all_tab_columns
                  WHERE   owner     = 'SCOTT'     -- Remember ot use UPPER CASE inside quotes
                  AND         table_name     = 'EMP'
         LOOP
              dbms_output.put_line (c.column_name || ' = column_name inside loop');
         END LOOP;
    END;
    /I'm confused about what you want to do, though.
    Do you want the PL/SQL code to write and/or execute an ALTER TABLE command for each column?

  • JDev 10.1.3.4: How to properly loop through the rows of a VO?

    Hi,
    This is a newbie question. Using JDeveloper 10.1.3.4 I am trying to loop through the rows of a view object. I am sure that the VO returns the following rows in that order:
    200809
    200902
    200906If I use this code (where termsOpen is the VO instance):
    while (termsOpen.hasNext()) {
       System.out.println(termsOpen.getCurrentRow().getAttribute("Term"));
    }it proves to be an endless loop and I get "200809" printed on the console endlessly. The API says that hasNext() "does not move the current row". A book says that the pointer initially is at row 0. I wonder why it prints the first row. So the code is changed to:
    while (termsOpen.hasNext()) {
       Row currRow = termsOpen.next();
       System.out.println(currRow.getAttribute("Term"));
    }But now I get only the last two rows printed on the console, and do not get to see the first row:
    200902
    200906What's wrong?
    Thanks for helping!
    Newman

    Hi, Branislav,
    Thank you for the suggestion.
    I tried that also. When the code is
    while (termsOpen.hasNext()) {
       System.out.println(termsOpen.getCurrentRow().getAttribute("Term"));
       termsOpen.next();
    }I get only the first two rows and last row is dropped:
    200809
    200902To get all the three row, I end up using this code:
    System.out.println(termsOpen.first().getAttribute("Term"));
    while (termsOpen.hasNext()) {
       Row currRow = termsOpen.next();
       System.out.println(currRow.getAttribute("Term"));
    }But that shouldn't be the way of doing the work. If I use a block of 50 lines of code to process each row, the code will have to be written once before the while loop and another time inside the while loop.
    The book which says that the pointer starts at the row slot before the first row is found on the internet, on p.469. It makes sense to me that the pointer starts at row 0. But unfortunately the actual copy of JDev 10.1.3.4 I am using behaves otherwise.
    Newman

  • Looping through 2 resultsets simultaneously

    I need to set up a loop in which I loop through 2 ResultSets simultaneously and compare them. I have tried to use a simple while (RS1.next() || RS2.next() ), but when I try to read data from RS2 I get an "Invalid Cursor state" error. From my experience with these errors, I think it just means that RS2 isn't looping, but I don't know how to fix it.
    Here's the loop I have:
    while (RS1.next() || RS2.next() ) {
    <%=RS1.getString("Name")%> <%=RS2.getString("Name")%>
    And just to avoid any confusion, what I have written is correct, both tables have a field called 'Name'.
    Can someone please help me?
    Chris

    Unfortunately, there is not necessarily a one-to-one relationship between the Note and Message. However, I am actually using 2 separate statement objects for the resultsets. I know exactly what you mean if there was in fact a 1-to-1 relationship, but unfortunately, since there isn't, I need 2 resultsets. I have tried a few other things since I wrote this and have come close. Here is what I've tried, so others know:
    I've tried using a boolean variable set to true at the beginning and if, after going through the loop, I am at the end of both recordsets, I set it to false. This worked when I didn't have any elements in one of the tables, but, for one reason or another, when I had data in both tables, I got the same Invalid Cursor State error.
    I've also tried using 2 separate boolean variables, one for each of the fields, but this also gives me this error.
    So if anyone else has any ideas to help me out, I'd appreciate it.
    Chris

  • Looping through records without hardcoding column identifiers

    Is it possible to call a nextval type function when looping through a recordset?
    I have a cursor which fetches records into a %rowtype variable. However, I was wondering is it possible to go through each record without having to call the column name, but rather incrementally moving from record to record
    i.e.
    cursor x is
    select a,b,c from d;
    record x%rowtype;
    open x;
    loop
    fetch x into record;
    htp.p(x.nextval (or its equivalent));
    exit when x%notfound;
    end loop;
    is this possible instead of
    htp.p(x.a);
    htp.p(x.b);
    htp.p(x.c);
    Thanks

    You probably want to hard-code the column names in your code.
    The alternative would be to use dynamic SQL and the DBMS_SQL package. That would drastically complicate the code, however, so it's generally not a great idea.
    Justin

Maybe you are looking for