Dyn SQL in Ref cursor?

Hi all,
I have a pkg as below and its err message in compile:
create or replace PACKAGE PKG_DARTS1 is
TYPE TY_PARTY_DETAIL1 IS RECORD (
     PTY_TYPE xxx.yyyy%TYPE
TYPE cur_partydetail1 IS REF CURSOR RETURN TY_PARTY_DETAIL1;
procedure SP_GetPartyDetail1(     c_partydetail1 OUT pkg_darts1.cur_partydetail1) ;
end PKG_DARTS1;
create or replace PACKAGE BODY PKG_DARTS1 as
procedure SP_GetPartyDetail1(     c_partydetail1 OUT pkg_darts1.cur_partydetail1)
AS
     sql_stmt VARCHAR2(2000);
BEGIN
     sql_stmt := 'select ''XXX'' FROM DUAL ';
     OPEN c_partydetail1 FOR sql_stmt;
EXCEPTION
     WHEN OTHERS THEN
          dbms_output.put_line(sqlerrm);
END SP_GetPartyDetail1;
END PKG_DARTS1;
.Warning: Package Body created with compilation errors.
Errors for PACKAGE BODY PKG_DARTS1:
LINE/COL ERROR
13/3 PL/SQL: Statement ignored
13/8 PLS-00455: cursor 'C_PARTYDETAIL1' cannot be used in dynamic SQL
OPEN statement
what's wrong with my syntax? anything I should care in constructing sql in ref cursor?
thx,
bean

You can't use strongly types ref cursors with dynamic SQL, you will have to use weakly typed.
Hth
Martin

Similar Messages

  • "java.sql.SQLException: Ref cursor is invalid" - Please help

    Hi everyone,
    I'm really having problem. I'm surrently calling a PL/SQL stored procedure from Java but I'm getting the following error:
    java.sql.SQLException: Ref cursor is invalid
    The procedure has 2 normal IN parameters and 1 ref cursor OUT parameter. Depending upon Parameter 1 a ref cursor may or may not be initialised.
    If Parameter 1 is "yes" then a ref cursor is called to retrieve some data and passed into the OUT. If Parameter 1 is set to "no" then the ref cursor is not initialised. It is here where the error is being hrown. Does anyone know why? Microsoft ADO doesn't seem to complain. Please help is needed. Thanks in advance.
    John

    Hi Justin,
    Thanks for replying. The Java code is a bit awkward to send because we're using several "home-made" wrapper objects to call SQL and stored procedures. In both cases I create a resultset object and only this one object is used irrespective if the first parameter is "yes" or "no", but a ref cursor is passed to the OUT parameter only on condition yes. Hence, the PL/SQL code takes the form similar to:
    OPEN curs FOR SELECT * FROM table;
    The "curs" is then put into the OUT of the procedure. When the parameter is "no" then the "curs" ref cursor in the PL/SQL procedure isn't even initialised like the above. At this point Java complains of an invalid ref cursor. I can try and piece togather the code but it may be very tricky.
    John

  • Dynamic sql and ref cursors URGENT!!

    Hi,
    I'm using a long to build a dynamic sql statement. This is limited by about 32k. This is too short for my statement.
    The query results in a ref cursor.
    Does anyone have an idea to create larger statement or to couple ref cursors, so I can execute the statement a couple of times and as an result I still have one ref cursor.
    Example:
    /* Determine if project is main project, then select all subprojects */
    for i in isMainProject loop
    if i.belongstoprojectno is null then
    for i in ProjectSubNumbers loop
    if ProjectSubNumbers%rowcount=1 then
    SqlStatement := InitialStatement || i.projectno;
    else
    SqlStatement := SqlStatement || PartialStatement || i.projectno;
    end if;
    end loop;
    else
    for i in ProjectNumber loop
    if ProjectNumber%rowcount=1 then
    SqlStatement := InitialStatement || i.projectno;
    else
    SqlStatement := SqlStatement || PartialStatement || i.projectno;
    end if;
    end loop;
    end if;
    end loop;
    /* Open ref cursor */
    open sql_output for SqlStatement;
    Thanks in advance,
    Jeroen Muis
    KCI Datasystems BV
    mailto:[email protected]

    Example for 'dynamic' ref cursor - dynamic WHERE
    (note that Reports need 'static' ref cursor type
    for building Report Layout):
    1. Stored package
    CREATE OR REPLACE PACKAGE report_dynamic IS
    TYPE type_ref_cur_sta IS REF CURSOR RETURN dept%ROWTYPE; -- for Report Layout only
    TYPE type_ref_cur_dyn IS REF CURSOR;
    FUNCTION func_dyn (p_where VARCHAR2) RETURN type_ref_cur_dyn;
    END;
    CREATE OR REPLACE PACKAGE BODY report_dynamic IS
    FUNCTION func_dyn (p_where VARCHAR2) RETURN type_ref_cur_dyn IS
    ref_cur_dyn type_ref_cur_dyn;
    BEGIN
    OPEN ref_cur_dyn FOR
    'SELECT * FROM dept WHERE ' | | NVL (p_where, '1 = 1');
    RETURN ref_cur_dyn;
    END;
    END;
    2. Query PL/SQL in Reports
    function QR_1RefCurQuery return report_dynamic.type_ref_cur_sta is
    begin
    return report_dynamic.func_dyn (:p_where);
    end;
    Regards
    Zlatko Sirotic
    null

  • Converting cursor to ref cursor in Report builder pl/sql

    Hi,
    I am trying to use dynamic sql in My report 's pl/sql code.
    I can not use execute Immediate statement since this feature is not suppoerted at client side and i am doing the coding In my local mchine and running the report loaclly.......???
    Another way to use dynamic sql is by using dbms_sql package.
    Using dbms_sql to run a sql will give me a normal cursor as an output.
    Since in report builder pl/sql only ref cursor is allowed as a return type from a function........the problem i m facing is conversion of the cursor to ref cursor......
    in oracle 11g we have a built in function in dbms_sql package that can be used for the conversion....
    i m using oracle 10 g where the above mentioned feature is not available............
    Please give some way to resolve this issue............!!!!!!!!!!!!
    Thanks in Advance.....!!!!!!!
    Abhishant

    You may use some stored procedures that will take full advantage of dynamic SQL. Make a stored proc that inserts rows in a global temporary table. You will call that stored proc in the afterpform trigger. And you will have the report querry select from the temporary table populated by the stored proc.
    I did some things like that.
    HTH

  • Ref Cursor over Implicit and explicit cursors

    Hi,
    In my company when writing PL/SQL procedure, everyone uses "Ref Cursor",
    But the article below, says Implicit is best , then Explicit and finally Ref Cursor..
    [http://www.oracle-base.com/forums/viewtopic.php?f=2&t=10720]
    I am bit confused by this, can any one help me to understand this?
    Thanks

    SeshuGiri wrote:
    In my company when writing PL/SQL procedure, everyone uses "Ref Cursor",
    But the article below, says Implicit is best , then Explicit and finally Ref Cursor..
    [http://www.oracle-base.com/forums/viewtopic.php?f=2&t=10720]
    I am bit confused by this, can any one help me to understand this?There is performance and there is performance...
    To explain. There is only a single type of cursor in Oracle - that is the cursor that is parsed and compiled by the SQL engine and stored in the database's shared pool. The "+client+" is then given a handle (called a SQL Statement Handle in many APIs) that it can use to reference that cursor in the SQL engine.
    The performance of this cursor is not determined by the client. It is determined by the execution plan and how much executing that cursor cost ito server resources.
    The client can be Java, Visual Basic, .Net - or a PL/SQL program. This client language (a client of SQL), has its own structures in dealing with that cursor handle received from the SQL engine.
    It can hide it from the developer all together - so that he/she does not even see that there is a statement handle. This is what implicit cursors are in PL/SQL.
    It can allow the developer to manually define the cursor structure - this is what explicit cursors, ref cursors, and DBMS_SQL cursors are in PL/SQL.
    Each of these client cursor structures provides the programmer with a different set of features to deal with SQL cursor. Explicit cursor constructs in PL/SQL do not allow for the use of dynamic SQL. Ref cursors and DBMS_SQL cursors do. Ref cursors do not allow the programmer to determine, at run-time, the structure of the SQL projection of the cursor. DBMS_SQL cursors do.
    Only ref cursors can be created in PL/SQL and then be handed over to another client (e.g. Java/VB) for processing. Etc.
    So each of the client structures/interfaces provides you with a different feature set for SQL cursors.
    Choosing implicit cursors for example does not make the SQL cursor go faster. The SQL engine does not know and does not care, what client construct you are using to deal with the SQL cursor handle it gave you. It does not matter. It does not impact its SQL cursor performance.
    But on the client side, it can matter - as your code in dealing with that SQL cursor determines how fast your interaction with that SQL cursor is. How many context switches you make. How effectively you use and re-use the SQL (e.g. hard parsing vs soft parsing vs re-using the same cursor handle). Etc.
    Is there any single client cursor construct that is better? No.
    That is an ignorant view. The client language provides a toolbox, where each tool has a specific application. The knowledgeable developer will use the right tool for the job. The idiot developer will select one tool and use it as The Hammer to "solve" all the problems.

  • Ref Cursor is invalid error

    Hi,
    I have written a jdbc application which return a ref cursor. I use ResultSet rset = ((OracleCallableStatement)call).getCursor (1); to get the result set according to jdbc user guide. Compilation is ok but when I run it, the error is:
    Exception in thread "main" java.sql.SQLException: Ref cursor is invalid
    at java.lang.Throwable.fillInStackTrace(Native Method)
    at java.lang.Throwable.fillInStackTrace(Compiled Code)
    at java.lang.Throwable.<init>(Compiled Code)
    at java.lang.Exception.<init>(Exception.java:42)
    at java.sql.SQLException.<init>(SQLException.java:43)
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:114)
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:156)
    at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:219)
    at oracle.jdbc.driver.OracleStatement.getCursorValue(OracleStatement.java:2544)
    at oracle.jdbc.driver.OracleCallableStatement.getCursor(OracleCallableStatement.java:583)
    at useCursor.main(useCursor.java:41)
    I attach the code for ur reference. Pls point out to me what's wrong.
    import oracle.sql.*;
    import oracle.jdbc.oracore.Util;
    import java.sql.*;
    import java.io.*;
    import oracle.jdbc.driver.*;
    class useCursor{
    private static final String Server = "job.comp.edu.au:1521:testing";
    private static final String Username = "user";
    private static final String Password = "org";
    public static void main (String args [])
    throws SQLException
    // Connect to the database
    // You can put a database name after the @ sign in the connection URL.
    Connection conn = getConnection ();
    String elements[] = new String[1];
    elements[0] = "select * from product";
    // Create the stored procedure
    init (conn);
    ArrayDescriptor desc = ArrayDescriptor.createDescriptor("STR_VARRAY3", conn);
    ARRAY newArray = new ARRAY(desc, conn, elements);
    // Prepare a PL/SQL call
    CallableStatement call =
    conn.prepareCall ("{ ? = call java_refcursor.job_listing (?)}");
    // Find out all the SALES person
    call.registerOutParameter (1, OracleTypes.CURSOR);
    ((OraclePreparedStatement)call).setARRAY(2, newArray);
    call.execute ();
    ResultSet rset = ((OracleCallableStatement)call).getCursor (1);
    // Dump the cursor
    while (rset.next ())
    System.out.println (rset.getString ("AUTHOR"));
    // Utility function to create the stored procedure
    static void init (Connection conn)
    throws SQLException
    Statement stmt = conn.createStatement ();
    try
    stmt.execute ("DROP TYPE str_varray3");
    catch (SQLException e)
    // the above drop statements will throw exceptions
    // if the types and tables did not exist before. Just ingore it.
    stmt.execute ("CREATE TYPE str_varray3 AS VARRAY(10) OF VARCHAR2(50)");
    stmt.execute ("create or replace package java_refcursor as " +
    " type myrctype is ref cursor; "+
    " function job_listing (sa str_varray3) return myrctype; " +
    "end java_refcursor;");
    stmt.execute ("create or replace package body java_refcursor as " +
    " function job_listing (sa str_varray3) return myrctype is " +
    " rc myrctype; " +
    " i number; " +
    " begin " +
    " while sa.COUNT >= i" +
    " loop " +
    " open rc for sa(1);" +
    " exit when rc%NOTFOUND; " +
    " i := i + 1; " +
    " end loop; " +
    " return rc; " +
    " end; " +
    "end java_refcursor;");
    public static Connection getConnection(){
    Connection con = null;
    try {
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    catch (SQLException sqlex ) {
    System.err.println("Unable register Oracle driver");
    sqlex.printStackTrace();
    try {
    con = DriverManager.getConnection("jdbc:oracle:thin:@" + Server, Username, Password);
    catch (SQLException sqlex) {
    System.err.println("Unable to connect");
    sqlex.printStackTrace();
    return con;
    Please advise me. Thank you very much.
    null

    i have found out my mistake
    it lacks of i := 0;
    my mind was not so ok then.. :)

  • REF CURSOR FOR LOOP WITHOUT FETCHING

    I am trying to run the following PL/SQL with REF CURSOR.
    I am using FOR .. IN <REF CURSOR NAME> LOOP construct. The compiler fails at FOR v_Each IN v_Cursor line complaining that the v_Cursor is not delared. You can see the v_cursor is defined in the DECLARE section. If I change the FOR v_Each IN v_Cursor to
    FETCH v_Cursor INTO v_RecordHolder;
    EXIT WHEN v_Cursor%NOTFOUND;
    then the PL/SQL will run. Does anyone know why I can not use my prefer construct?
    If I use FETCH .. INTO, since my select statment returns a result of severla joins, I have to create a Record() structure for all the columns returns, is there a way to create a Record() type that only has one field%ROWTYE.
    /******* my code starts here ********/
    DECLARE
    v_StartDate DATE := TO_DATE('05-01-2003','MM/DD/YYYY');
    TYPE t_CursorRef IS REF CURSOR;
    v_Cursor t_CursorRef;
    BEGIN
    OPEN v_Cursor FOR
    SELECT DISTINCT E.*, P.P_CODE, C.PT_ID
    FROM TABLE1 E, TABLE2 P, TABLE3 I, TABLE4 C
    WHERE E.P_ID = P.P_ID AND E.E_ID = I.E_ID
    AND E.P_ID = C.PT_ID (+)
    AND TRUNC(E.E_DATETIME) >= TO_DATE(v_StartDate)
    AND E.DIS_ID = 1
    AND RTRIM(P.A_CODE) = 'A'
    AND ((MONTHS_BETWEEN(SYSDATE,P.P_BEGIN)/12 > 40) AND (MONTHS_BETWEEN(SYSDATE,P.P_END)/12 < 85))
    AND (RTRIM(I.E_D_CODE) IN ('V81.1','272.2','272.4','401.9','305.1','278.00','272.0') AND RTRIM(I.E_D_CODE) NOT IN ('414.9','414.00','250.00','436','414.01'));
    FOR v_Each IN v_Cursor LOOP
    DBMS_OUTPUT.PUT_LINE('Inside the loop P_ID is ' || TO_CHAR(v_Each.P_ID));
    CLOSE v_Cursor;
    END LOOP; /* FOR v_Each */

    Please post technical questions in the respective forums : PL/SQL
    Is it mandatory for you to use REF CURSOR, else you could use the following code which gives the same result.
    DECLARE
    v_StartDate DATE := TO_DATE('05-01-2003','MM/DD/YYYY');
    CURSOR v_Cursor(inputdate DATE) IS
    SELECT DISTINCT E.*, P.P_CODE, C.PT_ID
    FROM TABLE1 E, TABLE2 P, TABLE3 I, TABLE4 C
    WHERE E.P_ID = P.P_ID AND E.E_ID = I.E_ID
    AND E.P_ID = C.PT_ID (+)
    AND TRUNC(E.E_DATETIME) >= inputdate
    AND E.DIS_ID = 1
    AND RTRIM(P.A_CODE) = 'A'
    AND ((MONTHS_BETWEEN(SYSDATE,P.P_BEGIN)/12 > 40) AND (MONTHS_BETWEEN(SYSDATE,P.P_END)/12 < 85))
    AND (RTRIM(I.E_D_CODE) IN ('V81.1','272.2','272.4','401.9','305.1','278.00','272.0') AND RTRIM(I.E_D_CODE) NOT IN ('414.9','414.00','250.00','436','414.01'));
    BEGIN
    FOR v_Each IN v_Cursor(v_StartDate) LOOP
    DBMS_OUTPUT.PUT_LINE('Inside the loop P_ID is ' || TO_CHAR(v_Each.P_ID));
    END LOOP; /* FOR v_Each */
    END;

  • ORA-01008 with ref cursor and dynamic sql

    When I run the follwing procedure:
    variable x refcursor
    set autoprint on
    begin
      Crosstab.pivot(p_max_cols => 4,
       p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by job order by deptno) rn from scott.emp group by job, deptno',
       p_anchor => Crosstab.array('JOB'),
       p_pivot  => Crosstab.array('DEPTNO', 'CNT'),
       p_cursor => :x );
    end;I get the following error:
    ^----------------
    Statement Ignored
    set autoprint on
    begin
    adsmgr.Crosstab.pivot(p_max_cols => 4,
    p_query => 'select job, count(*) cnt, deptno, row_number() over (partition by
    p_anchor => adsmgr.Crosstab.array('JOB'),
    p_pivot => adsmgr.Crosstab.array('DEPTNO', 'CNT'),
    p_cursor => :x );
    end;
    ORA-01008: not all variables bound
    I am running this on a stored procedure as follows:
    create or replace package Crosstab
    as
        type refcursor is ref cursor;
        type array is table of varchar2(30);
        procedure pivot( p_max_cols       in number   default null,
                         p_max_cols_query in varchar2 default null,
                         p_query          in varchar2,
                         p_anchor         in array,
                         p_pivot          in array,
                         p_cursor in out refcursor );
    end;
    create or replace package body Crosstab
    as
    procedure pivot( p_max_cols          in number   default null,
                     p_max_cols_query in varchar2 default null,
                     p_query          in varchar2,
                     p_anchor         in array,
                     p_pivot          in array,
                     p_cursor in out refcursor )
    as
        l_max_cols number;
        l_query    long;
        l_cnames   array;
    begin
        -- figure out the number of columns we must support
        -- we either KNOW this or we have a query that can tell us
        if ( p_max_cols is not null )
        then
            l_max_cols := p_max_cols;
        elsif ( p_max_cols_query is not null )
        then
            execute immediate p_max_cols_query into l_max_cols;
        else
            RAISE_APPLICATION_ERROR(-20001, 'Cannot figure out max cols');
        end if;
        -- Now, construct the query that can answer the question for us...
        -- start with the C1, C2, ... CX columns:
        l_query := 'select ';
        for i in 1 .. p_anchor.count
        loop
            l_query := l_query || p_anchor(i) || ',';
        end loop;
        -- Now add in the C{x+1}... CN columns to be pivoted:
        -- the format is "max(decode(rn,1,C{X+1},null)) cx+1_1"
        for i in 1 .. l_max_cols
        loop
            for j in 1 .. p_pivot.count
            loop
                l_query := l_query ||
                    'max(decode(rn,'||i||','||
                               p_pivot(j)||',null)) ' ||
                                p_pivot(j) || '_' || i || ',';
            end loop;
        end loop;
        -- Now just add in the original query
        l_query := rtrim(l_query,',')||' from ( '||p_query||') group by ';
        -- and then the group by columns...
        for i in 1 .. p_anchor.count
        loop
            l_query := l_query || p_anchor(i) || ',';
        end loop;
        l_query := rtrim(l_query,',');
        -- and return it
        execute immediate 'alter session set cursor_sharing=force';
        open p_cursor for l_query;
        execute immediate 'alter session set cursor_sharing=exact';
    end;
    end;
    /I can see from the error message that it is ignoring the x declaration, I assume it is because it does not recognise the type refcursor from the procedure.
    How do I get it to recognise this?
    Thank you in advance

    Thank you for your help
    This is the version of Oracle I am running, so this may have something to do with that.
    Oracle9i Enterprise Edition Release 9.2.0.8.0 - Production
    With the Partitioning, OLAP and Oracle Data Mining options
    JServer Release 9.2.0.8.0 - Production
    I found this on Ask Tom (http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:3027089372477)
    Hello, Tom.
    I have one bind variable in a dynamic SQL expression.
    When I open cursor for this sql, it gets me to ora-01008.
    Please consider:
    Connected to:
    Oracle8i Enterprise Edition Release 8.1.7.4.1 - Production
    JServer Release 8.1.7.4.1 - Production
    SQL> declare
      2    type cur is ref cursor;
      3    res cur;
      4  begin
      5    open res for
      6    'select * from (select * from dual where :p = 1) connect by 1 = 1'
      7    using 1;
      8  end;
      9  /
    declare
    ERROR at line 1:
    ORA-01008: not all variables bound
    ORA-06512: at line 5
    SQL> declare
      2    type cur is ref cursor;
      3    res cur;
      4  begin
      5    open res for
      6    'select * from (select * from dual where :p = 1) connect by 1 = 1'
      7    using 1, 2;
      8  end;
      9  /
    PL/SQL procedure successfully completed.
    And if I run the same thing on 10g -- all goes conversely. The first part runs ok, and the second
    part reports "ORA-01006: bind variable does not exist" (as it should be, I think). Remember, there
    is ONE bind variable in sql, not two. Is it a bug in 8i?
    What should we do to avoid this error running the same plsql program code on different Oracle
    versions?
    P.S. Thank you for your invaluable work on this site.
    Followup   June 9, 2005 - 6pm US/Eastern:
    what is the purpose of this query really?
    but it would appear to be a bug in 8i (since it should need but one).  You will have to work that
    via support. I changed the type to tarray to see if the reserved word was causing a problem.
    variable v_refcursor refcursor;
    set autoprint on;
    begin 
         crosstab.pivot (p_max_cols => 4,
                 p_query => 
                   'SELECT job, COUNT (*) cnt, deptno, ' || 
                   '       ROW_NUMBER () OVER ( ' || 
                   '          PARTITION BY job ' || 
                   '          ORDER BY deptno) rn ' || 
                   'FROM   emp ' ||
                   'GROUP BY job, deptno',
                   p_anchor => crosstab.tarray ('JOB'),
                   p_pivot => crosstab.tarray ('DEPTNO', 'CNT'),
                   p_cursor => :v_refcursor);
    end;
    /Was going to use this package as a stored procedure in forms but I not sure it's going to work now.

  • 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.

  • Ref cursor and dynamic sql

    Hi..
    I'm using a ref cursor query to fetch data for a report and works just fine. However i need to use dynamic sql in the query because the columns used in the where condition and for some calculations may change dynamically according to user input from the form that launches the report..
    Ideally the query should look like this:
    select
    a,b,c
    from table
    where :x = something
    and :y = something
    and (abs(:x/:y........)
    The user should be able to switch between :x and :y
    Is there a way to embed dynamic sql in a ref cursor query in Reports 6i?
    Reports 6i
    Forms 6i
    Windows 2000 PRO

    Hello Nicola,
    You can parameterize your ref cursor by putting the query's select statement in a procedure/function (defined in your report, or in the database), and populating it based on arguments accepted by the procedure.
    For example, the following procedure accepts a strongly typed ref cursor and populates it with emp table data based on the value of the 'mydept' input parameter:
    Procedure emp_refcursor(emp_data IN OUT emp_rc, mydept number) as
    Begin
    -- Open emp_data for select all columns from emp where deptno = mydept;
    Open emp_data for select * from emp where deptno = mydept;
    End;
    This procedure/function can then be called from the ref cursor query program unit defined in your report's data model, to return the filled ref cursor to Reports.
    Thanks,
    The Oracle Reports Team.

  • Report using ref cursor or dynamic Sql

    Hi,
    I never create a report using a ref cursor or a dynamic sql. Could any one help me to solve the below issue.
    I have 2 tables.
    1. Student_Record
    2. Student_csv_help
    Student_Record the main table where the data is stored.
    Student_csv_help will contain the all the column names of the Student_record.
    CREATE TABLE Student_CSV_HELP
    ENTRY_ID NUMBER,
    RAW_NAME VARCHAR2(40 BYTE),
    DESC_NAME VARCHAR2(1000 BYTE),
    IN_OUTPUT_LIST VARCHAR2(1 BYTE)
    SET DEFINE OFF;
    Insert into TOA_CSV_HELP
    (ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
    Values
    (1, 'S_ID', 'Student ID', 'Y');
    Insert into TOA_CSV_HELP
    (ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
    Values
    (2, 'S_Name', 'Student Name', 'Y');
    Insert into TOA_CSV_HELP
    (ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
    Values
    (3, 'S_Join_date', 'Joining Date', 'Y');
    Insert into TOA_CSV_HELP
    (ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
    Values
    (4, 'S_Address', 'Address', 'Y');
    Insert into TOA_CSV_HELP
    (ENTRY_ID, RAW_NAME, DESC_NAME, IN_OUTPUT_LIST)
    Values
    (5, 'S_Fee', 'Tution Fee', 'N');
    commit;
    CREATE TABLE Student_record
    S_ID NUMBER,
    S_Name VARCHAR2(100 BYTE),
    S_Join_date date,
    S_Address VARCHAR2(360 BYTE),
    S_Fee Number
    Insert into Student_record
    (S_ID, S_Name, S_Join_date, S_Address,S_Fee)
    Values
    (101, 'john', TO_DATE('12/17/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94777', 2000);
    Insert into Student_record
    (S_ID, S_Name, S_Join_date, S_Address,S_Fee)
    Values
    (102, 'arif', TO_DATE('12/18/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94444', 3000);
    Insert into Student_record
    (S_ID, S_Name, S_Join_date, S_Address,S_Fee)
    Values
    (103, 'raj', TO_DATE('12/19/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94555', 2500);
    Insert into Student_record
    (S_ID, S_Name, S_Join_date, S_Address,S_Fee)
    Values
    (104, 'singh', TO_DATE('12/20/2009 08:00:00', 'MM/DD/YYYY HH24:MI:SS'), 'CA-94666', 2000);
    Commit;
    Now my requirement is:
    I have a form with Student_record data block. When i Click on print Button on this form. It will open another window which has Student_CSV_HELP.DESC_NAME and a check box before this.
    The window look like as below:
    check_box       DESC_NAME+
    X                   S_ID+
    --                   S_Name+
    X                   S_Join_date+
    X                   S_Address+
    --                  S_Fee+
    X  means check box checked.+
    --  means check box Unchecked.+
    After i selected these check boxes i will send 2 parameters to the report server
    1. a string parameter to the report server which has the value 'S_ID,S_Join_date,S_Address' (p_column_name := 'S_ID,S_Join_date,S_Address');
    2. the s_id value from the student_record block (p_S_id := '101');
    Now my requirement is when i click on run. I need a report like as below:
    Student ID : 101+
    Joining Date : 12/17/2009 08:00:00+
    Address : CA-94777+
    This is nothing but the ref cursor should run like as below:
    Select S_id from student_record block S_id = :p_S_id;
    Select S_Join_date from student_record block S_id = :p_S_id;
    Select S_Address from student_record block S_id = :p_S_id;
    So, according to my understanding i have to select the columns at the run time. I dont have much knowledge in creating reports using ref cursor or dynamic sql.
    So please help me to solve this issue.
    Thanks in advance.

    Plain sql should satisfy your need. Try ....
    Select S_id, S_Join_date, S_Address
    from student_record
    where S_id = :p_S_id

  • How to descrbe a ref cursor from a PL/SQL prog?

    Hi,
    here is a sample of the my problem
    let suppose a table country :
    create table country(country_code VARCHAR2(3), country_name VARCHAR2(50));
    then a package containing different procedures among them, this one :
    PL/SQL prog
    create or replace package country_pkg as
    type rec1 is ref cursor return country%rowtype;
    Procedure get_all_countries(rec in out rec1);
    blablabla ...
    END country_pkg;
    in the package body, i have the following code :
    create or replace package body country_pkg as
    procedure get_all_countries(rec IN OUT rec1) is
    begin
    if not rec%open then
    open rec for select * from country order by country_name;
    end if;
    exception
    when NO_DATA_FOUND then
    close rec;
    end get_all_countries;
    blablabla....
    end;
    Then in the C program
    (*proc)->request->command = "begin get_all_countries(:rec); end;"
    checkerr(&connect, \
         OCIStmtPrepare(connect->stmthp,\
         connect->errhp,\
         (*proc)->request->command,\
         strlen((*proc)->request->command),\
         OCI_NTV_SYNTAX, OCI_DEFAULT));
    checkerr(&connect, \
         OCIHandleAlloc((dvoid*)(connect->envhp),\
         (dvoid**) &((*proc)->stmthp), OCI_HTYPE_STMT,
    (size_t) 0,\
         (dvoid**) 0));
    bndhp = (OCIBind**) g_malloc0((*proc)->argnum*sizeof(OCIBind*));
    for(i = 0; i < (*proc)->argnum; i++)
    switch ((*proc)->desc->type)
    case 102:
    checkerr(&connect,
    OCIBindByPos(connect->stmthp, &bndhp[j],
    connect->errhp,
         i+1,&((*proc)->stmthp), (sb4) 0,
         SQLT_REF, (dvoid*) 0, (ub2*) 0, (ub2*) 0,
    (ub4) 0,
         (ub4*) 0, (ub4) OCI_DEFAULT));
    default:
    some code ....
    checkerr(&connect, \
         OCIStmtExecute(connect->svchp, connect->stmthp,\
         connect->errhp, 1, (ub4) 0, (OCISnapshot*) 0,\
         (OCISnapshot*) 0, OCI_DEFAULT));
    parm_status = OCIParamGet(connect->stmthp, OCI_HTYPE_STMT,connect->errhp, (dvoid**)&arg, 0);
    while(parm_status == OCI_SUCCESS)
    OCIAttrGet((dvoid*) arg, OCI_DTYPE_PARAM,
    (dvoid*)type,0, (ub4) OCI_ATTR_NUM_PARAMS,
    connect->errhp);
    counter++;
    parm_status = OCIParamGet(connect->stmthp,
    OCII_HTYPE_STMT,connect->errhp,
    (dvoid**)&arg, counter);
    This piece of code doesn't work as 'arg' is always NULL
    and OCIParamGet retruns OCI_SUCCESS.
    I'm certainly missing something but I don't see what. Could anyone help me to get that piece of code working?
    regards,
    Raphael

    unfortunately, not yet!
    I dropped the matter for now, I'll come back on it later.
    On your side, let me know if you find something interesting on that topic by posting a message here.

  • Problem with XSU when trying to execute pl/sql package returning ref cursor

    Hi,
    I'm exploring xsu with 8i database.
    I tried running sample program which I took from oracle
    documentation. Here is the details of these.
    ------create package returning ref cursor---
    CREATE OR REPLACE package testRef is
         Type empRef IS REF CURSOR;
         function testRefCur return empRef;
    End;
    CREATE OR REPLACE package body testRef is
    function testRefCur RETURN empREF is
    a empREF;
    begin
    OPEN a FOR select * from emp;
    return a;
    end;
    end;
    ---------package successfully created-----
    Now I use java program to generate xml data from ref cursor
    ------------java program ----------
    import org.w3c.dom.*;
    import oracle.xml.parser.v2.*;
    import java.sql.*;
    import oracle.jdbc.driver.*;
    import oracle.xml.sql.query.OracleXMLQuery;
    import java.io.*;
    public class REFCURt
    public static void main(String[] argv)
    throws SQLException
    String str = null;
    Connection conn = getConnection("scott","tiger"); //
    create connection
    // Create a ResultSet object by calling the PL/SQL function
    CallableStatement stmt =
    conn.prepareCall("begin ? := testRef.testRefCur();
    end;");
    stmt.registerOutParameter(1,OracleTypes.CURSOR); // set
    the define type
    stmt.execute(); // Execute the statement.
    ResultSet rset = (ResultSet)stmt.getObject(1); // Get the
    ResultSet
    OracleXMLQuery qry = new OracleXMLQuery(conn,rset); //
    prepare Query class
         try
    qry.setRaiseNoRowsException(true);
    qry.setRaiseException(true);
    qry.keepCursorState(true); // set options (keep the
    cursor alive..
         System.out.println("..before printing...");
    while ((str = qry.getXMLString())!= null)
    System.out.println(str);
         catch(oracle.xml.sql.OracleXMLSQLNoRowsException ex)
    System.out.println(" END OF OUTPUT ");
    qry.close(); // close the query..!
    // qry.close(); // close the query..!
    // Note since we supplied the statement and resultset,
    closing the
    // OracleXMLquery instance will not close these. We would
    need to
    // explicitly close this ourselves..!
    stmt.close();
    conn.close();
    // Get the connection given the user name and password..!
    private static Connection getConnection(String user, String
    passwd)
    throws SQLException
    DriverManager.registerDriver(new
    oracle.jdbc.driver.OracleDriver());
    Connection conn = DriverManager.getConnection
    ("jdbc:oracle:thin:@xxxx:1521:yyyy",user,passwd);
    return conn;
    when I ran the program after successful compilation,I got the
    following error
    ==========
    Exception in thread "main" oracle.xml.sql.OracleXMLSQLException:
    1
    at oracle.xml.sql.core.OracleXMLConvert.getXML(Compiled
    Code)
    at oracle.xml.sql.query.OracleXMLQuery.getXMLString
    (OracleXMLQuery.java:263)
    at oracle.xml.sql.query.OracleXMLQuery.getXMLString
    (OracleXMLQuery.java:217)
    at oracle.xml.sql.query.OracleXMLQuery.getXMLString
    (OracleXMLQuery.java:194)
    at REFCURt.main(Compiled Code)
    ============================
    Can anybody tell me why I'm getting this error.Am I missing any
    settings?
    thanks

    We are using 8.1.7 Oracle db with latest xdk loaded.
    am I missing any settings?

  • How to print/store in file the ref cursor in pl/sql block ?

    How to print/store in file the ref cursor in pl/sql block ?.

    How to print/store in file the ref cursor in pl/sql block ?.You question is quite confusing?
    So, i'm providing link in this manner.
    For RefCursor,
    http://www.oracle-base.com/articles/misc/UsingRefCursorsToReturnRecordsets.php
    http://www.oracle.com/technology/oramag/code/tips2003/042003.html
    For UTL_FILE,
    http://www.morganslibrary.org/reference/utl_file.html
    Regards.
    Satyaki De.
    Updated with new morgan library link.
    Edited by: Satyaki_De on Feb 24, 2010 9:03 PM

  • REF CURSOR in PL/SQL BLOCK

    I am trying to return a ref cursor from a function in a package. I am trying to execute this through SQL Plus and cannot seem to get the code correct this is what I have. Please help. How do I display the output? I tried a CURSOR FOR loop, but got syntactical error saying it was being used inproperly.
    DECLARE
         v_rec      adp_vsp.grc_vsp;
         v_fname ps_personal_data.first_name%TYPE;
         v_lname ps_personal_data.last_name%TYPE;
    BEGIN
         v_fname := 'John';
         v_lname := 'Barr';
         v_rec := adp_vsp.f_get_vsp(v_fname,v_lname);
    END;

    If you want to do it manually, you need to loop through the cursor and fetch the results:
    sql>create or replace procedure p_show_emps(p_rc out sys_refcursor)
      2  is
      3  begin
      4    open p_rc for select empno, ename from emp where rownum <= 5;
      5  end;
      6  /
    Procedure created.
    sql>declare
      2    v_rc     sys_refcursor;
      3    v_empno  emp.empno%type;
      4    v_ename  emp.ename%type;
      5  begin
      6    p_show_emps(v_rc);
      7    loop
      8      fetch v_rc into v_empno, v_ename;
      9      exit when v_rc%notfound;
    10      dbms_output.put_line( v_empno || ', ' || v_ename );
    11    end loop;   
    12    close v_rc;
    13  end;
    14  /
    7369, SMITH
    7499, ALLEN
    7521, WARD
    7566, JONES
    7654, MARTIN
    PL/SQL procedure successfully completed.

Maybe you are looking for