Opening a ref cursor using CLOB variable

Is there any way to open a ref cusor using CLOB variable.
When I am opening on CLOB variable , I am getting an error like 'Missing Expression'
Please help me

For 10g...
SQL> ed
Wrote file afiedt.buf
  1  declare
  2    v_large_sql  CLOB;
  3    v_num        NUMBER := 0;
  4    v_upperbound NUMBER;
  5    v_sql        DBMS_SQL.VARCHAR2S;
  6    v_cur        INTEGER;
  7    v_ret        NUMBER;
  8  begin
  9    -- Build a very large SQL statement in the CLOB
10    LOOP
11      IF v_num = 0 THEN
12        v_large_sql := 'CREATE VIEW vw_tmp AS SELECT ''The number of this row is : '||to_char(v_num,'fm0999999')||''' as col1 FROM DUAL';
13      ELSE
14        v_large_sql := v_large_sql || ' UNION ALL SELECT ''The number of this row is : '||to_char(v_num,'fm0999999')||''' as col1 FROM DUAL';
15      END IF;
16      v_num := v_num + 1;
17      EXIT WHEN DBMS_LOB.GETLENGTH(v_large_sql) > 40000 OR v_num > 800;
18    END LOOP;
19    DBMS_OUTPUT.PUT_LINE('Length:'||DBMS_LOB.GETLENGTH(v_large_sql));
20    DBMS_OUTPUT.PUT_LINE('Num:'||v_num);
21    --
22    -- Now split that large SQL statement into chunks of 256 characters and put in VARCHAR2S array
23    v_upperbound := CEIL(DBMS_LOB.GETLENGTH(v_large_sql)/256);
24    FOR i IN 1..v_upperbound
25    LOOP
26      v_sql(i) := DBMS_LOB.SUBSTR(v_large_sql
27                                 ,256 -- amount
28                                 ,((i-1)*256)+1 -- offset
29                                 );
30    END LOOP;
31    --
32    -- Now parse and execute the SQL statement
33    v_cur := DBMS_SQL.OPEN_CURSOR;
34    DBMS_SQL.PARSE(v_cur, v_sql, 1, v_upperbound, FALSE, DBMS_SQL.NATIVE);
35    v_ret := DBMS_SQL.EXECUTE(v_cur);
36    DBMS_OUTPUT.PUT_LINE('View Created');
37* end;
SQL> /
Length:40015
Num:548
View Created
PL/SQL procedure successfully completed.
SQL> select count(*) from vw_tmp;
  COUNT(*)
       548
SQL> select * from vw_tmp where rownum <= 10;
COL1
The number of this row is : 0000000
The number of this row is : 0000001
The number of this row is : 0000002
The number of this row is : 0000003
The number of this row is : 0000004
The number of this row is : 0000005
The number of this row is : 0000006
The number of this row is : 0000007
The number of this row is : 0000008
The number of this row is : 0000009
10 rows selected.
SQL>

Similar Messages

  • Problem in opening a ref cursor.

    Hi,
    I'm getting the following error when i'm trying to open the ref cursor. PL/SQL: ORA-22905: cannot access rows from a non-nested table item
    What i'm trying to do is I'm dumping the data into pl/sql table and i want retrieving the by using a ref cursor. Please see the code and help me out.
    CREATE OR REPLACE PACKAGE CPS_RECR.pg_pool_status AS
      TYPE pool_rec IS RECORD (
       status  varchar2(50)
      ,stsno number
      ,stscode varchar2(5)
      ,candidatename varchar2(200)
      ,monyear varchar2(10)
      ,yyyymm number
      ,stscnt number
      --type rec_sts_tab is table of number ;--index by pls_integer;
      type pool_tab IS table of pool_rec index by binary_integer;
      type pool_cv is REF CURSOR return pool_rec;
    FUNCTION pool_status_query(p_start_date in date,p_end_date in  date,p_invitedtopoolbit  in number,p_showedForPoolBit in  number)
       RETURN pool_tab;--pool_cv ;
      cursor cur_pool(p_start_date date,p_end_date date,p_invitedtopoolbit number,p_showedForPoolBit number)
      is
         SELECT   distinct to_char(date1,'yyyymm')yearmonth
                  FROM acs100data a,
                     acs100_candidate_verification b,                
                     acs100_candidate_pool d
                 WHERE UPPER (a.basic_email) = UPPER (b.email)
                 AND (b.candidate_status IN ('FORL', 'FWRT') or BITAND (b.candidate_status_bit, 4 ) > 0
                  or BITAND (b.candidate_status_bit, 2) > 0)                         
                 AND d.pool_id = b.pool_id
                 AND pool_date BETWEEN p_start_date AND p_end_date
                 AND is_tentative_date IS NULL  ;
      cursor cur_name(p_yyyymm varchar2,p_cond number,p_start_date date,p_end_date date)
      is
      select *
      from (select distinct (case
                                when p_cond = 0 and b.candidate_status = 'FORL'
                                   then (last_name || first_name)
                                when p_cond = 1 and b.candidate_status = 'FWRT'
                                   then (last_name || first_name)
                                when p_cond = 2
                                and bitand (b.candidate_status_bit, p_cond) > 0
                                   then (last_name || first_name)
                                when p_cond = 4
                                and bitand (b.candidate_status_bit, p_cond) > 0
                                   then (last_name || first_name)
                             end
                            ) candidatename
                       from acs100data a,
                            acs100_candidate_verification b,
                            acs100_candidate_pool d
                      where upper (a.basic_email) = upper (b.email)
                        and d.pool_id = b.pool_id
                        and pool_date between p_start_date and p_end_date
                        and to_char (date1, 'yyyymm') = p_yyyymm
                        and is_tentative_date is null)
    where candidatename is not null;  
    END pg_pool_status;
    CREATE OR REPLACE PACKAGE BODY CPS_RECR.pg_pool_status
    AS
       FUNCTION pool_status_query (
          p_start_date         IN   DATE,
          p_end_date           IN   DATE,
          p_invitedtopoolbit   IN   NUMBER,
          p_showedforpoolbit   IN   NUMBER
          RETURN pool_tab--pool_cv
       IS
          tab_pool    pool_tab;
          temp_rf    pool_cv;
          n_index     NUMBER         := 1;
          --rec_sts_data  rec_sts_tab;
          n_stscnt    NUMBER;
          vc_status   VARCHAR2 (100);
          vc_label  varchar2(1000);
          vc_name  varchar2(100);
       BEGIN
          tab_pool.DELETE;
          vc_label :='Opening Pool cursor';
          FOR rec_pool IN cur_pool (p_start_date,
                                    p_end_date,
                                    p_invitedtopoolbit,
                                    p_showedforpoolbit
          LOOP
              if cur_pool%notfound then
                exit;
              end if;
             vc_label :='Opening p_cond cursor';
             FOR p_cond IN 0 .. 3
             LOOP
                n_stscnt := 0;
                vc_status := NULL;
                begin
                    SELECT   SUM
                                (NVL
                                    (COUNT
                                        (CASE
                                            WHEN p_cond = 0
                                            AND b.candidate_status = 'FORL'
                                               THEN (last_name || first_name)
                                            WHEN p_cond = 1
                                            AND b.candidate_status = 'FWRT'
                                               THEN (last_name || first_name)
                                            WHEN p_cond = 2
                                            AND BITAND (b.candidate_status_bit,
                                                        p_cond) > 0
                                               THEN (last_name || first_name)
                                            WHEN p_cond = 4
                                            AND BITAND (b.candidate_status_bit,
                                                        p_cond) > 0
                                               THEN (last_name || first_name)
                                         END
                                     0
                                ) cnt,
                             DECODE (p_cond,
                                     0, 'FAILED WRITTEN TEST',
                                     1, 'FAILED **** TEST',
                                     2, 'Invited for Pool',
                                     4, 'Showed up for Pool'
                                    ) status
                        INTO n_stscnt,
                             vc_status
                        FROM acs100data a,
                             acs100_candidate_verification b,
                             acs100_candidate_pool d
                       WHERE UPPER (a.basic_email) = UPPER (b.email)
                         AND d.pool_id = b.pool_id
                         AND pool_date BETWEEN p_start_date AND p_end_date
                         AND TO_CHAR (date1, 'yyyymm') = rec_pool.yearmonth
                         AND is_tentative_date IS NULL
                    GROUP BY candidate_status,
                             b.candidate_status_bit,
                             DECODE (p_cond,
                                     0, 'FAILED WRITTEN TEST',
                                     1, 'FAILED **** TEST',
                                     2, 'Invited for Pool',
                                     4, 'Showed up for Pool'
                  exception
                     when no_data_found
                     then
                        n_stscnt :=0;
                        vc_status :=null;
                 end;
                vc_label :='Opening name cursor';         
                FOR rec_name IN cur_name (rec_pool.yearmonth,
                                          p_cond,
                                          p_start_date,
                                          p_end_date
                LOOP
                   if cur_name%notfound then
                   exit;
                   end if;
                   tab_pool (n_index).yyyymm := rec_pool.yearmonth;
                   tab_pool (n_index).stscnt := n_stscnt;
                   tab_pool (n_index).status := vc_status;
                   tab_pool (n_index).candidatename := rec_name.candidatename;
                   dbms_output.put_line('tab_pool(n_index).yyyymm  : '||tab_pool(n_index).yyyymm);
                   dbms_output.put_line('tab_pool(n_index).stscnt : '||tab_pool(n_index).stscnt);
                   dbms_output.put_line('tab_pool(n_index).status : '||tab_pool(n_index).status);
                   dbms_output.put_line('tab_pool(n_index).candidatename : '||tab_pool(n_index).candidatename);
                   vc_name :=rec_name.candidatename;
                END LOOP;
                n_index := n_index + 1;
             END LOOP;
          END LOOP;      
          RETURN tab_pool;
       exception
         when others
         then
             dbms_output.put_line('error :'||vc_label||'--'||  vc_name); 
       END;
    END pg_pool_status;
    ---run script
    DECLARE
      RetVal CPS_RECR.PG_POOL_STATUS.pool_tab;
      P_START_DATE DATE;
      P_END_DATE DATE;
      P_INVITEDTOPOOLBIT NUMBER;
      P_SHOWEDFORPOOLBIT NUMBER;
    temp_cv CPS_RECR.PG_POOL_STATUS.pool_cv;
    BEGIN
      P_START_DATE := to_date('09/01/2008','mm/dd/yyyy');
      P_END_DATE := to_date('09/30/2008','mm/dd/yyyy');
      P_INVITEDTOPOOLBIT := 2;
      P_SHOWEDFORPOOLBIT := 4;
      open temp_cv for select * from  table((CPS_RECR.PG_POOL_STATUS.POOL_STATUS_QUERY ( P_START_DATE, P_END_DATE, P_INVITEDTOPOOLBIT, P_SHOWEDFORPOOLBIT )) );
      end loop;
    exception
       when others
       then
          dbms_output.put_line(sqlerrm);
    END;

    Satyaki,
    It doesn't help me out. I'm worndering one of code sample is working fine. i didn't my current is giving the problem.
    FYI, please see the some code i followed.
    SQL> Create or replace PACKAGE cv IS
      2     type comp_rec is RECORD
      3               (deptno number,
      4                ename  varchar(10),
      5                compensation number);
      6     type comp_tbl IS table of comp_rec;
      7     function get_coll return comp_tbl pipelined;
      8     temp_tbl comp_tbl := comp_tbl();
      9     type comp_cv is REF CURSOR return comp_rec;
    10  end;
    11  /
    Package created.
    SQL> Create or replace PACKAGE body cv IS
      2     function get_coll return comp_tbl pipelined
      3     is
      4     begin
      5      for i in 1..temp_tbl.count loop
      6       pipe row(temp_tbl(i));
      7      end loop;
      8      return;
      9     end;
    10  end;
    11  /
    Package body created.
    SQL> declare
      2     temp_cv cv.comp_cv;
      3     rc cv.comp_rec;
      4  begin
      5           cv.temp_tbl.delete;
      6           cv.temp_tbl.extend;
      7    cv.temp_tbl(1).deptno:=10;
      8    cv.temp_tbl(1).ename:='1223';
      9    cv.temp_tbl(1).compensation:=10;
    10  
    11          -- erroring out
    12   open temp_cv for select * from  table(cv.get_coll);
    13          fetch temp_cv into rc;
    14          dbms_output.put_line('Deptno is ' || rc.deptno);
    15          dbms_output.put_line('ename is ' || rc.ename);
    16  end;
    17  /
    Deptno is 10
    ename is 1223
    PL/SQL procedure successfully completed.

  • How to retrieve data from a REF CURSOR using OCI 8.0?

    I found an example in Oracle docs (shown below) that discusses how to bind a REF CURSOR for later data retrieval, but it does not explain actually how to do the later data retrieval.
    I hope someone can explain it to me. Thanks
    The OCI provides the ability to bind and define PL/SQL REF CURSORs and nested tables. An application can use a statement handle to bind and define these types of variables. As an example, consider this PL/SQL block:
    static const text plsql_block = (text )
    "begin \
    OPEN :cursor1 FOR SELECT empno, ename, job, mgr, sal, deptno \
    FROM emp_rc WHERE job=:job ORDER BY empno; \
    OPEN :cursor2 FOR SELECT * FROM dept_rc ORDER BY deptno; \
    end;";
    An application would allocate a statement handle for binding, by calling OCIHandleAlloc(), and then bind the :cursor1 placeholder to the statement handle, as in the following code, where :cursor1 is bound to stm2p. Note that the handle allocation code is not included here.
    err = OCIStmtPrepare (stm1p, errhp, (text *) nst_tab, strlen(nst_tab),
    OCI_NTV_SYNTAX, OCI_DEFAULT);
    err = OCIBindByName (stm1p, (OCIBind **) bndp, errhp,
    (text *)":cursor1", (sb4)strlen((char *)":cursor1"),
    (dvoid *)&stm2p, (sb4) 0, SQLT_RSET, (dvoid *)0,
    (ub2 *)0, (ub2 *)0, (ub4)0, (ub4 *)0, (ub4)OCI_DEFAULT);
    In this code, stm1p is the statement handle for the PL/SQL block, while stm2p is the statement handle which is bound as a REF CURSOR for later data retrieval. A value of SQLT_RSET is passed for the dty parameter.

    ( sorry, i forgot the Link where i get this html fiLes, so i just copy-paste here )
    ( maybe it can heLp you a bit. -- it's heLp me, for sure )
    And the following is thanks to Brett Rosen :
    I noticed that you didn't have an OCI entry
    on http://osi.oracle.com/~tkyte/ResultSets/index.html .
    Here is OCI code to do this (Oracle 81) if you want to include it on
    that page.
    Some error checking and cleanup has been removed, but the below should
    work. (once dbname has been replaced appropriately)
    Brett
    int main(int argc, char* argv[])
    OCIError* pOciError;
    char* pConnectChar = "dbname";
    char* pUsernameChar = "scott";
    char* pPasswordChar = "tiger";
    int answer;
    OCIStmt* pOciStatement;
    char* sqlCharArray = "BEGIN :success := sp_ListEmp; END;";
    int id;
    char ename[40];
    OCIEnv* g_pOciEnvironment = NULL;
    OCIServer* g_pOciServer = NULL;
    OCISession* g_pOciSession = NULL;
    OCISvcCtx* g_pOciServiceContext = NULL;
    sb2* pIndicator=0;
    sb2* pIndicator2=0;
    sb2* pIndicator3=0;
    OCIDefine* pOciDefine;
    OCIDefine* pOciDefine2;
    OCIBind* pBind;
    OCIStmt* cursor;
    answer = OCIInitialize(OCI_THREADED, NULL, NULL, NULL, NULL);
    answer = OCIEnvInit(&g_pOciEnvironment, OCI_DEFAULT, 0, NULL);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&pOciError, OCI_HTYPE_ERROR, 0, NULL);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&g_pOciSession, OCI_HTYPE_SESSION, 0, NULL);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&g_pOciServer, OCI_HTYPE_SERVER, 0, NULL);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&g_pOciServiceContext, OCI_HTYPE_SVCCTX, 0, NULL);
    answer = OCIServerAttach(g_pOciServer, pOciError, (unsigned char *)pConnectChar, strlen(pConnectChar),
    OCI_DEFAULT);
    answer = OCIAttrSet(g_pOciSession, OCI_HTYPE_SESSION, (unsigned char *)pUsernameChar, strlen(pUsernameChar),
    OCI_ATTR_USERNAME, pOciError);
    answer = OCIAttrSet(g_pOciSession, OCI_HTYPE_SESSION, (unsigned char *)pPasswordChar, strlen(pPasswordChar),
    OCI_ATTR_PASSWORD, pOciError);
    answer = OCIAttrSet(g_pOciServiceContext, OCI_HTYPE_SVCCTX, g_pOciServer, 0, OCI_ATTR_SERVER, pOciError);
    answer = OCIAttrSet(g_pOciServiceContext, OCI_HTYPE_SVCCTX, g_pOciSession, 0, OCI_ATTR_SESSION, pOciError);
    answer = OCISessionBegin(g_pOciServiceContext, pOciError, g_pOciSession, OCI_CRED_RDBMS, OCI_DEFAULT);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)(&pOciStatement), OCI_HTYPE_STMT, 0, NULL);
    answer = OCIStmtPrepare(pOciStatement, pOciError, (unsigned char *)sqlCharArray, strlen(sqlCharArray),
    OCI_NTV_SYNTAX, OCI_DEFAULT);
    answer = OCIHandleAlloc(g_pOciEnvironment, (void **)(&cursor), OCI_HTYPE_STMT, 0, NULL);
    answer = OCIBindByPos(pOciStatement,&pBind, pOciError, 1, &cursor, 0,SQLT_RSET,
    pIndicator2, 0,NULL, 0,0,OCI_DEFAULT);
    answer = OCIStmtExecute(g_pOciServiceContext, pOciStatement, pOciError, 1, 0, NULL, NULL,
    OCI_COMMIT_ON_SUCCESS);
    answer = OCIDefineByPos(cursor,&pOciDefine, pOciError,2,&id,sizeof(int),
    SQLT_INT,pIndicator, 0, 0,OCI_DEFAULT);
    answer = OCIDefineByPos(cursor,&pOciDefine2, pOciError,1,ename,40,
    SQLT_STR,pIndicator3, 0, 0,OCI_DEFAULT);
    if (answer == 0)
    while ((answer = OCIStmtFetch(cursor,pOciError, 1,OCI_FETCH_NEXT,OCI_DEFAULT)) == 0)
    printf("fetched id %d and name %s\n",id,ename);
    answer = OCIHandleFree(pOciError, OCI_HTYPE_ERROR);
    return 0;
    }

  • Ref Cursor Using Dynamic Query

    Hi,
    I need to use the ref cursor to fetch result from dynamic query.
    e.g.
    Open ref_test_tbl for Select * from tbl1 where tbl1.field1= :1
    and tbl1.field2 =:2 using i_v1,i_v2;
    The thing is i_v1, i_v2 are dynamic.
    i.e. using clause can include i_v3, i_v4 also.
    How to include dynamic variables in the using clause.
    thanks

    > How to include dynamic variables in the using clause.
    Cannot using a ref cursor.. (and anyone that post code that writes dynamic PL/SQL in order to achieve this, I will call an idiot).
    What you should be using in PL/SQL is a DBMS_SQL cursor. This allows you to create a fully dynamic SQL statement with bind variables. E.g.
    select * from tbl1 where col1 = :1
    select * from tbl1 where col2 = :1 order by 2
    select * from tbl1 where col3 between :0 and :1
    Using this dynamically created SQL statement, you can parse it using DBMS_SQL, determine the number of bind variables, and bind each of these dynamically.
    You can then execute the SQL and again, dynamically, determine just what the projection of the cursor is. How many columns are returned, their names, data types, precision and so on.
    This is what APEX (see http://apex.oracle.com) use extensively in order to run SQLs and render these as reports - all dynamically.
    DBMS_SQL is detailed in the [url http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14258/d_sql.htm#BABEDAHF]Oracle® Database PL/SQL Packages and Types Reference manual.

  • Odd error while opening a ref cursor

    Hi.
    I have a procedure in a package that has both in and out parameters. One of those out parameters is a ref cursor. The procedure creates a dynamic query and then executes it, then it opens the cursor:
    PROCEDURE PROC(
    A IN VARCHAR2,
    B IN VARCHAR2,
    C OUT TYPES.cursorType; --(TYPES is a package whose only use is to declare a cursor type)
    ) IS
    --DECLARATIONS
    OPEN C FOR 'SELECT A, B, C, D...';
    END;
    When I execute the package in an anonymous block it throws the error:
    ORA-00938: not enough arguments for function, just in the line where the cursor is being opened.
    Any ideas?

    is everything defined correctly?
    create or replace package types  as
      type cursorType is ref cursor;
    end types;
    SQL> set serveroutput on
    SQL> declare
      2 
      3    ref_C types.cursorType;
      4   
      5    v_a varchar2(1);
      6    v_b varchar2(1);
      7    v_c varchar2(1);
      8    v_d varchar2(1);
      9   
    10    procedure Proc (a in varchar2
    11                   ,b in varchar2
    12                   ,C out types.cursorType) as
    13 
    14      begin
    15        open C for 'select :1, :2, ''c'', ''d'' from dual' using a, b;
    16    end  Proc;
    17  begin
    18 
    19 
    20    Proc('a', 'b', ref_C);
    21   
    22    fetch ref_C into v_a, v_b, v_c, v_d;
    23    if (ref_C%found) then
    24      dbms_output.put_line(v_a);
    25      dbms_output.put_line(v_b);
    26      dbms_output.put_line(v_c);
    27      dbms_output.put_line(v_d);
    28    end if;
    29   
    30   
    31  end;
    32  /
    a
    b
    c
    dP;
    Edited by: bluefrog on Feb 18, 2010 6:07 PM

  • Need help about ref cursor using like table

    Hi Guys...
    I am devloping package function And i need help about cursor
    One of my function return sys_refcursor. And the return cursor need to be
    join another table in database . I don't have to fetch all rows in cursor
    All i need to join ref cursor and another table in sql clause
    like below
    select a.aa , b.cc form ( ref_cursor ) A, table B
    where A.dd = B.dd
    I appeciate it in advance

    My understanding is that you have a function that returns a refcursor and is called by a java app.
    Because this is a commonly used bit of code, you also want to reuse this cursor in other bits of sql and so you want to include it like table in a bit of sql and join that refcursor to other tables.
    It's not as easy as you might hope but you can probably achieve this with pipelined functions.
    Is it a direction that code should be going down? yes, eventually. I like the idea of pulling commonly used bits of code into a SQL statement especially into the WITH section, provided it could be used efficiently by the CBO.
    Is it worth the effort given what you have to do currently to implement it? possibly not.
    what else could you do? construct the sql statement independently of the thing that used it and reuse that sql statement rather than the refcursor it returns?
    Message was edited by:
    dombrooks

  • How to open a Ref cursor in Oracle Reports

    I have a stored procedure that returns a ref cursor as an output parameter. I want to call this stored procedure in Oracle Reports After Form trigger. I am having trouble with the syntax of the output parameter. Event_record is the name of the cursor.
    After Form Trigger
    pkg_DEAL_WHITESHEET_CONCERTS.prc_Event_Information(:p_field_6,event_record);
    Error: Event_record must be declared

    Re-Write the procedure as Package Spec and Body. Declare the REFCursor in the Package Spec. Probably that helps.

  • Using a Variable for Table Name  with a cursor

    Hello All
    Is it possible to use a Parameter passed to a procedure as the table name
    in a cursor selection statment. I thought the below would work but I get
    a error. Does anyone have any ideas?? The Error is listed below to.
    Here's the code I just complied
    CREATE OR REPLACE PROCEDURE Dup_Add(NEWQATABLE IN VARCHAR2) IS
    CURSOR c1 IS SELECT MUNI,PROV FROM NEWQATABLE GROUP BY MUNI, PROV;
    c1rec c1%ROWTYPE;
    BEGIN
    OPEN c1;
    LOOP
    FETCH c1 INTO c1rec;
    EXIT WHEN c1%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(c1rec.MUNI);
    END LOOP;
    CLOSE c1;
    END;
    Here is the errors
    LINE/COL ERROR
    3/8 PLS-00341: declaration of cursor 'C1' is incomplete or malformed
    3/15 PL/SQL: SQL Statement ignored
    3/38 PLS-00201: identifier 'NEWQATABLE' must be declared
    5/7 PL/SQL: Item ignored
    10/3 PL/SQL: SQL Statement ignored
    10/17 PLS-00320: the declaration of the type of this expression is
    incomplete or malformed
    12/3 PL/SQL: Statement ignored
    12/24 PLS-00320: the declaration of the type of this expression is
    incomplete or malformed
    LINE/COL ERROR
    Thanks
    Peter

    If you are going to have a table name or a column name as a parameter, then you have to open the cursor dynamically. The following example uses Native Dynamic SQL (NDS) to open a ref cursor dynamically. I also eliminated the group by clause, since it is intended for use with aggregate functions and you weren't using an aggregate function. Also notice that there are some other differences in terms of defining variables and fetching and so forth.
    SQL> CREATE TABLE test_table
      2  AS
      3  SELECT deptno AS muni,
      4         dname  AS prov
      5  FROM   dept
      6  /
    Table created.
    SQL> CREATE OR REPLACE PROCEDURE Dup_Add
      2    (newqatable IN VARCHAR2)
      3  IS
      4    TYPE cursor_type IS REF CURSOR;
      5    c1 cursor_type;
      6    c1muni NUMBER;
      7    c1prov VARCHAR2 (20);
      8  BEGIN
      9    OPEN c1 FOR 'SELECT muni, prov FROM ' || newqatable;
    10    LOOP
    11      FETCH c1 INTO c1muni, c1prov;
    12      EXIT WHEN c1%NOTFOUND;
    13      DBMS_OUTPUT.PUT_LINE (c1muni || ' ' || c1prov);
    14    END LOOP;
    15    CLOSE c1;
    16  END;
    17  /
    Procedure created.
    SQL> SHOW ERRORS
    No errors.
    SQL> SET SERVEROUTPUT ON
    SQL> EXECUTE dup_add ('test_table')
    10 ACCOUNTING
    20 RESEARCH
    30 SALES
    40 OPERATIONS
    PL/SQL procedure successfully completed.

  • How do i return data, when my sql was opened in a ref cursor.

    In Pl/sql, I was been bunged in the following situation:
    I am opening a ref cursor, where i couldn't determine the return type. In that case how will i return the data for those sql.
    Sample code :
    Declare
    Type a_ref IS REF CURSOR;
    C1 a_ref;
    Begin
    Open c1 for ‘select a, b, c from D’;
    Fetch c1 into ??????;
    Close c1;
    End;
    My doubt resides in ??? part..
    The columns in the select clause will vary dynamically.
    Hence how can I declare my variable..
    Regards,
    Bala

    Well, nothing is over to change mind if possible. I think the knowledge of
    alternatives is always useful... :).
    As for DBMS_SQL, it's an alternative to ref cursors too, but surely inside PL/SQL:
    SQL> declare
      2   c integer;
      3   desc_t DBMS_SQL.DESC_TAB;
      4   col_cnt integer;
      5   type gvarray is varray(25) of varchar(40);
      6   values1 gvarray := gvarray();
      7   a integer;
      8  begin
      9   values1.extend(25);
    10   c := dbms_sql.open_cursor;
    11   DBMS_SQL.PARSE(c,'select hiredate,ename from emp' ,DBMS_SQL.NATIVE);
    12   DBMS_SQL.DESCRIBE_COLUMNS (
    13     c,
    14     col_cnt,
    15     desc_t);
    16   for j in 1..col_cnt loop
    17     dbms_sql.define_column(c,j,values1(j),40);
    18   end loop;
    19   a:=dbms_sql.execute(c);
    20   loop
    21     if dbms_sql.fetch_rows(c) > 0 then
    22      for j in 1..col_cnt loop
    23        dbms_sql.column_value(c,j,values1(j));
    24        dbms_output.put_line('Row number ' || j || ', column ' || desc_t(j).col_name || ', value
    25        || values1(j) );
    26      end loop;
    27     else
    28       exit;
    29     end if;
    30   end loop;
    31   dbms_sql.close_cursor(c);
    32  end;
    33  /
    Row number 1, column HIREDATE, value 17.12.80
    Row number 2, column ENAME, value SMITH
    Row number 1, column HIREDATE, value 20.02.81
    Row number 2, column ENAME, value ALLEN
    Row number 1, column HIREDATE, value 22.02.81
    Row number 2, column ENAME, value WARD
    Row number 1, column HIREDATE, value 02.04.81
    Row number 2, column ENAME, value JONES
    Row number 1, column HIREDATE, value 28.09.81
    Row number 2, column ENAME, value MARTIN
    Row number 1, column HIREDATE, value 01.05.81
    Row number 2, column ENAME, value BLAKE
    Row number 1, column HIREDATE, value 09.06.81
    Row number 2, column ENAME, value CLARK
    Row number 1, column HIREDATE, value 19.04.87
    Row number 2, column ENAME, value SCOTT
    Row number 1, column HIREDATE, value 17.11.81
    Row number 2, column ENAME, value KING
    Row number 1, column HIREDATE, value 08.09.81
    Row number 2, column ENAME, value TURNER
    Row number 1, column HIREDATE, value 23.05.87
    Row number 2, column ENAME, value ADAMS
    Row number 1, column HIREDATE, value 03.12.81
    Row number 2, column ENAME, value JAMES
    Row number 1, column HIREDATE, value 03.12.81
    Row number 2, column ENAME, value FORD
    Row number 1, column HIREDATE, value 23.01.82
    Row number 2, column ENAME, value MILLER
    PL/SQL procedure successfully completed.Rgds.

  • How to return integer used wit DMBS_SQL as ref cursor ?

    I am trying to return a ref cursor form a procedure to be used by xsql to output hierarchical XML.
    I created the query using the DBMS_SQL package, did an OPEN_CURSOR and then PARSE.
    Can I, and if so how, return the integer from the PARSE as a ref cursor out of my procedure ? According to the docs the integer in the PARSE is the ID number for a cursor.
    thanks,
    Reinier

    I suspect that you are a little confused. I doubt that what you are asking for is what you really need. I believe you want the contents of a ref cursor, not an integer that is the cursor id. Since you are using Oracle 8i, as mentioned in your other post, you don't need DBMS_SQL; You just need to open a ref cursor dynmacially. Please see my response to your other post:
    Re: Error while compiling form in AS 10g  deployed on Linux

  • Ref cursors and dynamic sql..

    I want to be able to use a fuction that will dynamically create a SQL statement and then open a cursor based on that SQL statement and return a ref to that cursor. To achieve that, I am trying to build the sql statement in a varchar2 variable and using that variable to open the ref cursor as in,
    open l_stmt for refcurType;
    where refcurType is a strong ref cursor. I am unable to do so because I get an error indication that I can not use strong ref cursor type. But, if I can not use a strong ref cursor, I will not be able to use it to build the report based on the ref cursor because Reports 9i requires strong ref cursors to be used. Does that mean I can not use dynamic sql with Reports 9i ref cursors? Else, how I can do that? Any documentation available?

    Philipp,
    Thank you for your reply. My requirement is that, sometimes I need to construct a whole query based on some input, and sometimes not. But the output record set would be same and the layout would be more or less same. I thought ref cursor would be ideal. Ofcourse, I could do this without dynamic SQL by writing the SQL multiple times if needed. But, I think dynamic SQL is a proper candidate for this case. Your suggestion to use lexical variable is indeed a good alternative. In effect, if needed, I could generate an entire SQL statement and place in some place holder (like &stmt) and use it as a static SQL query in my data model. In that case, why would one ever need ref cursor in reports? Is one more efficient over the other? My guess is, in the lexical variable case, part of the processing (like parsing) is done on the app server while in a function based ref cursor, the entire process takes place in the DB server and there is probably a better chance for re-use(?)
    Thanks,
    Murali.

  • [Solved] 27.8.4 How to Create a VO on a REF CURSOR - Missing first row

    Searching the forum I found: BC4J - Get one less row from view object.
    Dive into BC4J related  --REF CURSOR (Resultset)
    The first message did not have any answers, and the second had a follow up question - still no answers though - and I thought I would try a different title.
    (This is off topic, but it would be a great help if the search results also displayed the number of replys in the thread. That way, I wouldn't have to view the messages that don't have responses.)
    (This will be deployed on a server that has the ADF for JDeveloper 10.1.2 installed, so using that version of JDeveloper to develop the app.)
    Okay, back to the problem ==>
    I created a VO from a ref cursor, using the manual as a guide. When I run a page that displays a read only table of the view object, I am missing the first row. (Always the first row!) I don't have any order set, and if I call the ref cursor in a Java program for testing, I see all rows and the count is correct.
    One other point, when I call the page, I get the following validation error:
    Validation Error
    You must correct the following error(s) before proceeding:
    * JBO-29000: Unexpected exception caught: java.lang.ClassCastException, msg=null
    * null
    I still see the table, it is just missing the first row of data.
    In my form I have first, previous set, next set , and last
    navigation buttons. If I press last then first, the error goes away. I still don't see the missing row though.
    Any guidance would be appreciated! I can post my code, but it is pretty much the same code in the AdvancedViewObjectExamples.zip in the ViewObjectOnRefCursor example. I just substituted my two package calls (getRefCursor and getRefCursorCount).
    Thanks, Ken

    Went back to a backup copy of the source. Fixed the error. Now I'm back to just not being able to see the first row of data.
    Additional Note: I had removed fields in the display. Once I truncated the ps_txn table in the schema defined by the model, the data would display (Still without the first record.)
    Are there any examples that are more in depth than the few pages in the developer guide?
    Here is the code for my VOImpl class:
    package newslinearchive.model.datamodel;
    import java.math.BigDecimal;
    import java.sql.CallableStatement;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.sql.Timestamp;
    import java.sql.Types;
    import oracle.jbo.InvalidParamException;
    import oracle.jbo.JboException;
    import oracle.jbo.domain.Date;
    import oracle.jbo.domain.Number;
    import oracle.jbo.server.DBTransaction;
    import oracle.jbo.server.QueryCollection;
    import oracle.jbo.server.SQLBuilder;
    import oracle.jbo.server.ViewObjectImpl;
    import oracle.jbo.server.ViewRowImpl;
    import oracle.jbo.server.ViewRowSetImpl;
    import oracle.jdbc.driver.OracleCallableStatement;
    import oracle.jdbc.driver.OracleTypes;
    // --- File generated by Oracle ADF Business Components Design Time.
    // --- Custom code may be added to this class.
    // --- Warning: Do not modify method signatures of generated methods.
    public class SearchRefCursorImpl extends ViewObjectImpl {
    * This is the default constructor (do not remove)
    public SearchRefCursorImpl() {
    * Overridden framework method.
    * Executed when the framework needs to issue the database query for
    * the query collection based on this view object. One view object
    * can produce many related result sets, each potentially the result
    * of different bind variable values. If the rowset in query is involved
    * in a framework-coordinated master/detail viewlink, then the params array
    * will contain one or more framework-supplied bind parameters. If there
    * are any user-supplied bind parameter values, they will PRECEED the
    * framework-supplied bind variable values in the params array, and the
    * number of user parameters will be indicated by the value of the
    * numUserParams argument.
    protected void executeQueryForCollection(Object qc,Object[] params,int numUserParams) {
    storeNewResultSet(qc,retrieveRefCursor(qc,params));
    super.executeQueryForCollection(qc, params, numUserParams);
    * Overridden framework method.
    * Wipe out all traces of a built-in query for this VO
    protected void create() {
    getViewDef().setQuery(null);
    getViewDef().setSelectClause(null);
    setQuery(null);
    * Overridden framework method.
    * The role of this method is to "fetch", populate, and return a single row
    * from the datasource by calling createNewRowForCollection() and populating
    * its attributes using populateAttributeForRow().
    protected ViewRowImpl createRowFromResultSet(Object qc, ResultSet rs) {
    * We ignore the JDBC ResultSet passed by the framework (null anyway) and
    * use the resultset that we've stored in the query-collection-private
    * user data storage
    rs = getResultSet(qc);
    * Create a new row to populate
    ViewRowImpl r = createNewRowForCollection(qc);
    try {
    * Populate new row by attribute slot number for current row in Result Set
    // populateAttributeForRow(r,0, rs.getLong(1));
    // populateAttributeForRow(r,1, rs.getString(2));
    // populateAttributeForRow(r,2, rs.getString(3));
    // MASTERID NOT NULL NUMBER
    populateAttributeForRow(r,0, rs.getBigDecimal(1));
    //ID NOT NULL NUMBER
    populateAttributeForRow(r,1, rs.getBigDecimal(2));
    // CAID NOT NULL NUMBER
    populateAttributeForRow(r,2, rs.getBigDecimal(3));
    // LANGUAGE NOT NULL VARCHAR2(30)
    populateAttributeForRow(r,3, rs.getString(4));
    // IS_CURRENT_VERSION NOT NULL NUMBER(1)
    populateAttributeForRow(r,4, rs.getBigDecimal(5));
    // FOLDER_ID NOT NULL NUMBER
    populateAttributeForRow(r,5, rs.getBigDecimal(6));
    // FOLDER_REGION_ID NOT NULL NUMBER
    populateAttributeForRow(r,6, rs.getBigDecimal(7));
    // NAME NOT NULL VARCHAR2(256)
    populateAttributeForRow(r,7, rs.getString(8));
    // DISPLAY_NAME VARCHAR2(256)
    populateAttributeForRow(r,8, rs.getString(9));
    // ITEMTYPE NOT NULL VARCHAR2(30)
    populateAttributeForRow(r,9, rs.getString(10));
    // SUBTYPE VARCHAR2(40)
    populateAttributeForRow(r,10, rs.getString(11));
    // SUBTYPE_CAID NUMBER
    populateAttributeForRow(r,11, rs.getBigDecimal(12));
    // PARENT_ITEM_ID NUMBER
    populateAttributeForRow(r,12, rs.getBigDecimal(13));
    // CATEGORY_ID NUMBER
    populateAttributeForRow(r,13, rs.getBigDecimal(14));
    // CATEGORY_CAID NUMBER
    populateAttributeForRow(r,14, rs.getBigDecimal(15));
    // AUTHOR VARCHAR2(50)
    populateAttributeForRow(r,15, rs.getString(16));
    // DESCRIPTION VARCHAR2(2000)
    populateAttributeForRow(r,16, rs.getString(17));
    // PUBLISH_DATE NOT NULL DATE
    populateAttributeForRow(r,17, rs.getDate(18));
    // EXPIREMODE VARCHAR2(90)
    populateAttributeForRow(r,18, rs.getString(19));
    // EXPIRENUMBER NUMBER
    populateAttributeForRow(r,19, rs.getBigDecimal(20));
    // EXPIREDATE DATE
    populateAttributeForRow(r,20, rs.getDate(21));
    // IMAGE VARCHAR2(350)
    populateAttributeForRow(r,21, rs.getString(22));
    // KEYWORDS VARCHAR2(2000)
    populateAttributeForRow(r,22, rs.getString(23));
    // URL VARCHAR2(4000)
    populateAttributeForRow(r,23, rs.getString(24));
    // FILENAME VARCHAR2(350)
    populateAttributeForRow(r,24, rs.getString(25));
    // TEXT CLOB()
    populateAttributeForRow(r,25, rs.getClob(26));
    // FOLDER_LINK_ID NUMBER
    populateAttributeForRow(r,26, rs.getBigDecimal(27));
    // FOLDER_LINK_CAID NUMBER
    populateAttributeForRow(r,27, rs.getBigDecimal(28));
    // ACTIVE NOT NULL NUMBER(1)
    populateAttributeForRow(r,28, rs.getBigDecimal(29));
    // CAN_BE_CHECKEDOUT NUMBER(1)
    populateAttributeForRow(r,29, rs.getBigDecimal(30));
    // IS_ITEM_CHECKEDOUT NUMBER(1)
    populateAttributeForRow(r,30, rs.getBigDecimal(31));
    // CHECKER_USERNAME VARCHAR2(256)
    populateAttributeForRow(r,31, rs.getString(32));
    // CHECKOUT_DATE DATE
    populateAttributeForRow(r,32, rs.getDate(33));
    // FULLSCREEN NOT NULL NUMBER(1)
    populateAttributeForRow(r,33, rs.getBigDecimal(34));
    // INPLACE NOT NULL NUMBER(1)
    populateAttributeForRow(r,34, rs.getBigDecimal(35));
    // CREATEDATE NOT NULL DATE
    populateAttributeForRow(r,35, rs.getDate(36));
    // CREATOR NOT NULL VARCHAR2(256)
    populateAttributeForRow(r,36, rs.getString(37));
    // UPDATEDATE DATE
    populateAttributeForRow(r,37, rs.getDate(38));
    // UPDATOR VARCHAR2(256)
    populateAttributeForRow(r,38, rs.getString(39));
    // SECURITY VARCHAR2(25)
    populateAttributeForRow(r,39, rs.getString(40));
    // VISIBLE NOT NULL NUMBER(1)
    populateAttributeForRow(r,40, rs.getBigDecimal(41));
    // SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,41, rs.getBigDecimal(42));
    // CATEGORY_SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,42, rs.getBigDecimal(43));
    // AUTHOR_SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,43, rs.getBigDecimal(44));
    // CREATE_DATE_SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,44, rs.getBigDecimal(45));
    // ITEMTYPE_SEQUENCE NOT NULL NUMBER
    populateAttributeForRow(r,45, rs.getBigDecimal(46));
    catch (SQLException s) {
    throw new JboException(s);
    return r;
    * Overridden framework method.
    * Return true if the datasource has at least one more record to fetch.
    protected boolean hasNextForCollection(Object qc) {
    ResultSet rs = getResultSet(qc);
    boolean nextOne = false;
    try {
    nextOne = rs.next();
    * When were at the end of the result set, mark the query collection
    * as "FetchComplete".
    if (!nextOne) {
    setFetchCompleteForCollection(qc, true);
    * Close the result set, we're done with it
    rs.close();
    catch (SQLException s) {
    throw new JboException(s);
    return nextOne;
    * Overridden framework method.
    * The framework gives us a chance to clean up any resources related
    * to the datasource when a query collection is done being used.
    protected void releaseUserDataForCollection(Object qc, Object rs) {
    * Ignore the ResultSet passed in since we've created our own.
    * Fetch the ResultSet from the User-Data context instead
    ResultSet userDataRS = getResultSet(qc);
    if (userDataRS != null) {
    try {
    userDataRS.close();
    catch (SQLException s) {
    /* Ignore */
    super.releaseUserDataForCollection(qc, rs);
    * Overridden framework method
    * Return the number of rows that would be returned by executing
    * the query implied by the datasource. This gives the developer a
    * chance to perform a fast count of the rows that would be retrieved
    * if all rows were fetched from the database. In the default implementation
    * the framework will perform a SELECT COUNT(*) FROM (...) wrapper query
    * to let the database return the count. This count might only be an estimate
    * depending on how resource-intensive it would be to actually count the rows.
    public long getQueryHitCount(ViewRowSetImpl viewRowSet) {
    Long result = (Long)callStoredFunction(NUMBER,
    "PORTAL.SEARCH_REFCURSOR.getRefCursorCount",
    viewRowSet.getParameters(true));
    return result.longValue();
    // ------------- PRIVATE METHODS ----------------
    * Return a JDBC ResultSet representing the REF CURSOR return
    * value from our stored package function.
    * new Object[]{getNamedBindParamValue("Email",params)}
    private ResultSet retrieveRefCursor(Object qc, Object[] params) {
    ResultSet rs = (ResultSet)callStoredFunction(OracleTypes.CURSOR,
    "PORTAL.SEARCH_REFCURSOR.getRefCursor",
    null);
    return rs ;
    private Object getNamedBindParamValue(String varName, Object[] params) {
    Object result = null;
    if (getBindingStyle() == SQLBuilder.BINDING_STYLE_ORACLE_NAME) {
    if (params != null) {
    for (Object param : params) {
    Object[] nameValue = (Object[])param;
    String name = (String)nameValue[0];
    if (name.equals(varName)) {
    return (String)nameValue[1];
    throw new JboException("No bind variable named '"+varName+"'");
    * Store a new result set in the query-collection-private user-data context
    private void storeNewResultSet(Object qc, ResultSet rs) {
    ResultSet existingRs = getResultSet(qc);
    // If this query collection is getting reused, close out any previous rowset
    if (existingRs != null) {
    try {existingRs.close();} catch (SQLException s) {}
    setUserDataForCollection(qc,rs);
    hasNextForCollection(qc); // Prime the pump with the first row.
    * Retrieve the result set wrapper from the query-collection user-data
    private ResultSet getResultSet(Object qc) {
    return (ResultSet)getUserDataForCollection(qc);
    * Return either null or a new oracle.jbo.domain.Date
    private static Date nullOrNewDate(Timestamp t) {
    return t != null ? new Date(t) : null;
    * Return either null or a new oracle.jbo.domain.Number
    private static Number nullOrNewNumber(BigDecimal b) {
    try {
    return b != null ? new Number(b) : null;
    catch (SQLException s) { }
    return null;
    //----------------[ Begin Helper Code ]------------------------------
    public static int NUMBER = Types.NUMERIC;
    public static int DATE = Types.DATE;
    public static int VARCHAR2 = Types.VARCHAR;
    public static int CLOB = Types.CLOB;
    * Simplifies calling a stored function with bind variables
    * You can use the NUMBER, DATE, and VARCHAR2 constants in this
    * class to indicate the function return type for these three common types,
    * otherwise use one of the JDBC types in the java.sql.Types class.
    * NOTE: If you want to invoke a stored procedure without any bind variables
    * ==== then you can just use the basic getDBTransaction().executeCommand()
    * @param sqlReturnType JDBC datatype constant of function return value
    * @param stmt stored function statement
    * @param bindVars Object array of parameters
    * @return function return value as an Object
    protected Object callStoredFunction(int sqlReturnType, String stmt,
    Object[] bindVars) {
    CallableStatement st = null;
    try {
    st = getDBTransaction().createCallableStatement("begin ? := " + stmt +
    "; end;", 0);
    st.registerOutParameter(1, sqlReturnType);
    if (bindVars != null) {
    for (int z = 0; z < bindVars.length; z++) {
    st.setObject(z + 2, bindVars[z]);
    st.executeUpdate();
    return st.getObject(1);
    catch (SQLException e) {
    throw new JboException(e);
    finally {
    if (st != null) {
    try {
    st.close();
    catch (SQLException e) {}
    /**Gets the bind variable value for Email
    public String getEmail() {
    return (String)getNamedWhereClauseParam("Email");
    /**Sets <code>value</code> for bind variable Email
    public void setEmail(String value) {
    setNamedWhereClauseParam("Email", value);
    /**getEstimatedRowCount - overridden for custom java data source support.
    public long getEstimatedRowCount() {
    long value = super.getEstimatedRowCount();
    return value;
    Thanks, Ken

  • Populate a REF CURSOR from regular cursor...

    Hi all,
    I apologize if the answer to this is somewhere...I've been looking on the web for sometime and can't find an answer to the following problem. I have a Significant Events database that contains network based issues and problems. As problems are detected on the network an SE is issued and published. As the SE records are updated, NEW records are entered into the table and "linked" back to the original. Each update results in a new row. Thus, an SE with two updates would have a total of 3 lines. When the SE gets closed (set the column CLOSED to SYSDATE), only the "original" SE is closed, any updates are left open...aka, the CLOSED column is left null.
    That said, I need a way to get the original and/or latest updated SE rows from the table. Thus, I am trying to use a PL/SQL package. The PL/SQL "must" return a REF CURSOR as the results are being passed to a client process.
    My initial approach was within a PL/SQL procedure, I have an SQL statement that returns the SE originals. Once in that cursor I need to do the following:
    - Attempt to fetch any linked SE rows.
    - if no rows then
    - add the original to the REF CURSOR.
    - else
    - find latest SE update
    - add latest SE update to REF CURSOR.
    - end if
    My Question is : How do I manually "add" a row to a REF CURSOR?
    If this is not possible, is there a way to populate a REF CURSOR from maybe another construct like:
    TYPE ian_se_record is RECORD (
    se_id number
    ,linked_se_id number
    ,submitted date
    ,updated date
    ,closed date
    ,segroup varchar2(150)
    ,incident_start_time varchar2(150)
    ,business_units_affected varchar2(150)
    ,officenum varchar2(1500)
    ,sedetails varchar2(4000)
    TYPE ian_se_table is table of ian_se_record index by binary_integer;
    With the above construct I could:
    - Fill ian_se_table with the process described above.
    - And finally select off ian_se_table into the REF CURSOR?
    Any help would be greatly appreciated,
    adym

    Hi michaels,
    I've put your solution in place, but can't seem to get it to run. The two types were moved out of the package and into real types as you said. Here's the function, for brevity, I've remove some of the less important code:
    function ian_se_fetch return sys_refcursor
    is
        p_csr_events            sys_refcursor;
        cursor csr_items is
            select
                 se_id
        ...removed for brevity...
        /* END : csr_items  */
        ian_se_row     ian_se_record;
        ian_se_tbl     ian_se_table;
        l_lng_index    number;
        l_lng_linked   number;
        l_lng_id       number;
    begin
         * OPEN : Open the main cursor of originals...
        for the_item in csr_items loop
             * CHECK : Check for any updates to the original...
            l_lng_linked := 0;
            select count(*)
            into l_lng_linked
            from sig_se_t src
            where src.linked_se_id = the_item.se_id;
            l_lng_id := 0;    /* reset the se-id    */
            /* SE original...no linked records yet.    */
            if ( l_lng_linked = 0 ) then
                l_lng_id := the_item.se_id;
            /* SE updates...one or more updates are present.    */
            else
                begin
                    select
                         se_id
                    into l_lng_id
                    from sig_se_t src
                    where src.linked_se_id = the_item.se_id
                      and rownum = 1
                    order by updated desc; /* latest update    */
                exception
                    when too_many_rows then
                        l_lng_id := the_item.se_id;
                    when others then
                        l_lng_id := 0;
                end;
            end if;
            if ( l_lng_id != 0 ) then
                select
                     se_id
                    ,linked_se_id
                    ,submitted
                    ,updated
                    ,closed
                    ,segroup
                    ,incident_start_time
                    ,business_units_affected
                    ,officenum || decode( nvl(impact,'1')
                                      ,'1',''
                                      ,decode(impact
                                          ,'NA', ''
                                          ,':' || impact
                                  )                           impact
                    ,sedetails
                into ian_se_row.se_id
                    ,ian_se_row.linked_se_id
                    ,ian_se_row.submitted
                    ,ian_se_row.updated
                    ,ian_se_row.closed
                    ,ian_se_row.segroup
                    ,ian_se_row.incident_start_time
                    ,ian_se_row.business_units_affected
                    ,ian_se_row.officenum
                    ,ian_se_row.sedetails
                from sig_se_t src
                where src.se_id = l_lng_id;
                l_lng_index := nvl(ian_se_tbl.last,0)+1;
                ian_se_tbl(l_lng_index).se_id                   := ian_se_row.se_id;
                ian_se_tbl(l_lng_index).linked_se_id            := ian_se_row.linked_se_id;
                ian_se_tbl(l_lng_index).submitted               := ian_se_row.submitted;
                ian_se_tbl(l_lng_index).updated                 := ian_se_row.updated;
                ian_se_tbl(l_lng_index).closed                  := ian_se_row.closed;
                ian_se_tbl(l_lng_index).segroup                 := ian_se_row.segroup;
                ian_se_tbl(l_lng_index).incident_start_time     := ian_se_row.incident_start_time;
                ian_se_tbl(l_lng_index).business_units_affected := ian_se_row.business_units_affected;
                ian_se_tbl(l_lng_index).officenum               := ian_se_row.officenum;
                ian_se_tbl(l_lng_index).sedetails               := ian_se_row.sedetails;
            end if;
        end loop;
         * REF CURSOR : Open the ref cursor on the dataset...
        if ( nvl(ian_se_tbl.last,0) = 0 ) then
            p_csr_events := null;
        else
            open p_csr_events for
            select *
            from table (cast ( ian_se_tbl as ian_se_table ));
        end if;
        return p_csr_events;
    end;Here's the test. I keep getting the same error ORA-06530:
    SQL> variable v refcursor;
    SQL> exec :v:=pkg_ian.ian_se_fetch;
    BEGIN :v:=pkg_ian.ian_se_fetch; END;
    ERROR at line 1:
    ORA-06530: Reference to uninitialized composite
    ORA-06512: at "N0002501.PKG_IAN", line 131
    ORA-06512: at line 1
    SQL> print v
    ERROR:
    ORA-24338: statement handle not executedOther things I tried:
    - The ian_se_fetch() function was a procedure using an in out parameter...same error.
    - Wrote a small anonymous block and tried to LOOP/FETCH. Same ORA-06530 error.
    P.S. Line 131 of pkg_ian is the SELECT ... INTO ian_se_row.se_id, ...
    Any help would be greatly appreciated,
    tia,
    adym
    Message was edited by:
    alink

  • How to return a ref cursor from this dbms_sql?

    Hi,
    Can anyone show me how to return a ref cursor from this dbms_sql based procedure? I see 11g has a dbms_sql.to_refcursor(cursor_handle). How can this be done is 10g?
    Thx.
    CREATE OR REPLACE PROCEDURE Sample_Get_t
    p_sample_id sample.sample_id%TYPE,
    p_contract_id sample.contr_id%TYPE
    IS
    cursor_handle INT;
    sql_stmnt varchar2(500);
    rows_processed NUMBER;
    BEGIN
    sql_stmnt :=
    'SELECT
    sample_id,
    contr_id,
    rcpt_id
    FROM
    sample s
    WHERE
    s.contr_id = :1
    and s.sample_id = :2
    ORDER BY
    sample_id';
    cursor_handle := dbms_sql.open_cursor;
    dbms_sql.parse(cursor_handle, sql_stmnt, dbms_sql.native);
    dbms_sql.bind_variable(cursor_handle, ':1', p_contract_id);
    dbms_sql.bind_variable(cursor_handle, ':2', p_sample_id);
    rows_processed := dbms_sql.execute(cursor_handle);
    dbms_sql.close_cursor(cursor_handle);
    END Sample_Get_t;

    In 10 this cannot be done with dbms_sql (to my knowledge). There are a couple of other options.
    1) open the ref cursor for the dynamic statement using bind variables (or SYS_CONTEXT variables, which i prefer since they are much easier to deal with when you are dynamically adding predicates).
    declare
       wRefCursor  SYS_REFCURSOR;
    begin
       open wRefCursor for 'select * from all_objects where owner = :Logged_in_user' using user;
    end;
    /or using the context (the context will bind for you)
    declare
       wRefCursor  SYS_REFCURSOR;
    begin
       open wRefCursor for 'select * from all_objects where owner = SYS_CONTEXT(''CONTEXT_NAME'', ''VARIABLE_NAME'') ';
    end;
    /Be aware that contexts ALWAYS return varchar values, so if you are comparing to a number you should wrap it in TO_NUMBER, a date, TO_DATE and so on....
    2) change the DBMS_SQL to do an insert into a global temporary table and return the ref cursor which select's * from GTT;
    3) upgrade to Oracle 11 :)

  • Stored procedure - ref cursor - no rows

    Hello,
    I am stumped. Hopefully another pair of eyes will see what mine cannot. I am calling a stored procedure that accepts a single output parameter [the proc has been dumbed down to limit variables of my problem] that is a ref cursor. When I make the call I get now data. I have used both adapter and datareaders. If I call the proc from another proc I can loop through the results. I am including the code of my c# function and the stored proc.
    The version number of my Oracle.DataAccess.dll is 10.1.0.303.
    ** Stored Proc ***********************
    TYPE refcursor is ref cursor ;
    procedure P_CUSTOMER_INFO_GET_SLIM( thecur out refcursor )
    is
    begin
    open thecur for
    select *
    from customer_info
    where rownum < 21;
    end P_CUSTOMER_INFO_GET_SLIM;
    ** C# Func ***************************
              private DataSet _FetchCustomerData2(string CustNbr, string ShipToSuffix)
                   string                         sc = "PKG_CUSTOMER_CONTACT.P_CUSTOMER_INFO_GET_SLIM";
                   OracleConnection     con = new OracleConnection(_Database.GetConnection().ConnectionString);
                   OracleCommand               cmd = new OracleCommand(sc, con);
                   OracleDataAdapter da = new OracleDataAdapter(cmd);
                   DataSet ds = new DataSet();
                   // must pass strings with data
                   if (CustNbr.Length==0 || ShipToSuffix.Length==0)
                        return null;
                   try
                        // we are calling a stored proc so set it
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.Add("thecur", OracleDbType.RefCursor, DBNull.Value, ParameterDirection.Output);
                        da.Fill(ds, "Customer"); // no data ?????????????????
                        // Close and Dispose OracleConnection object
                        con.Close();
                        con.Dispose();
                        return ds;

    Hey all,
    I ended up declaring a variable in the proc as refcursor and opening it. Then I assigned the out parameter ref cursor to the variable. That took care of it. See below.
    Thanks,
    Mike
    procedure P_CUSTOMER_INFO_GET(
    CustomerNumber in varchar2
    ,ShipToSuffix in varchar2
    ,thecur out refcursor
    is
    -- variable declarations
    mycur refcursor;
    begin
    open mycur for
    select CORP_CODE
    ,CUST_NUMBER
    ,CUST_SHIP_TO_SFFX
    ,CUST_BILL_TO_SUFF
    ,CUST_AR_OFF_CODE
    ,CUST_NAME
    ,CUST_SHIP_BILL_IND
    ,CUST_SHIP_VIA_CODE
    ,CUST_CLASS_CODE
    ,CUST_TYPE_CODE
    ,CUST_PRICE_CODE
    ,DISC_MKUP_CODE
    ,TRADE_DISC_CODE
    ,CUST_N_D_ACCT_NO
    ,CUST_PRY_PRICE_AGR
    ,CUST_ADDR_1
    ,CUST_ADDR_2
    ,CUST_ADDR_3
    ,CUST_CITY
    ,CUST_STATE
    ,CUST_ZIP
    ,CUST_COUNTRY_CODE
    ,CUST_FAX_NO
    ,CUST_FAX_NO_EXP
    ,CUST_PHONE_NO
    ,CUST_PHONE_NO_EXP
    ,CUST_CRDT_LIM_CODE
    ,CUST_CREDIT_STATUS
    ,CUST_CRED_CARD_NO
    ,CUST_CC_EXP_DATE
    ,CUST_DUNNING_FLAG
    ,CUST_ID
    ,CUST_SP_FILE_IND
    ,CUST_ST_TAX_CODE
    ,LAST_MAINT_DATE
    from customer_info
    where CUST_NUMBER = CustomerNumber
    and CUST_SHIP_TO_SFFX = ShipToSuffix;
    -- send the cursor back
    thecur := mycur;

Maybe you are looking for

  • ITunes match for two libraries on one computer

    Whenever I try to enable iTunes Match in the latest iTunes beta, it says "This computer is already associated with an Apple ID." I cannot proceed with scanning my library. In the other account, with their Apple ID, it works. There are two user accoun

  • Problem of Chart in Web template

    hi friends, I  have created a chart in a web template,  however the chart is displaying the material number along with the calendar week, is it possible to have it only display the calendar week?  I also wanted to know if it is possible to insert a t

  • ITunes 6.1 will not launch

    After upgrading from iTunes 4 to 6, iTunes will not launch at all. Neither will the new version of Quicktime 7 that I installed at the same time. After clicking on the iTunes icon in the dock, the icon bounces once, but the application will not launc

  • Difference between message type and idoc type

    Hi difference between message type and idoc type Regards Rama

  • Finder crashes when right click

    Hey, I am having a problem with my finder crashing/restarting every time I want to right click or even if I want to ctrl+click on a file. It works if I want to right click on a folder but crashes every time when I right click on individual files. I a