Return XML from REF CURSOR

It appears to be fairly straight-forward to get XML from a SQL query using the XML SQL Utility.
Is it possible to use this utility (or another) to get XML from a cursor variable as well? I would like to generate overloaded get_xml functions in a PL/SQL package that will accept either SQL or a weak type REF CURSOR and return XML.

Thanks for the help. Actually, I just bought your book and was getting ready to do some research. This should get me pointed in the right direction.
Does the PL/SQL API lack this functionality? I wasn't sure whether to implement this in PL/SQL or Java, but the decision may be made for me...

Similar Messages

  • Sorting the results returned by a Ref cursor

    Hi All,
    I have a scenario where i am asked to sort results returned by a ref cursor.
    I have to pass the column to be sorted as the Input parameter to a stored procedure. I tried using 'order by sorting_parameter' in the ref cursor's select query, but it is not sorting the results. It is not throwing any error even.
    Please help.
    Many Thanks...

    Hi
    i came across the below reply for a thread with the similar query as above.
    <<
    Justin Cave
    Posts: 10,696
    From: Michigan, USA
    Registered: 10/11/99
    Re: sort data in ref cursor
    Posted: Feb 3, 2005 10:30 AM in response to: [email protected] Reply
    No. You could sort the data in the SQL statement from which the REF CURSOR was created, but once you have a REF CURSOR, you cannot do anything but fetch from it.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC
    >>
    So, the results from a ref cursor cant be sorted?? There is no way out?
    Kindly advise.

  • Wanted to fetch data from ref cursor to nested pl/sql table getting an erro

    create or replace type "DEPT12" as object(dno number(2),dname varchar2(30),loc varchar2(50));
    create or replace type dept_tab as table of "DEPT12"
    create or replace type "LOC12" as object(locno number,loc_name varchar2(100))
    create or replace type loc_tab as table of "LOC12"
    create or replace type dept_loc_rec1 as object (dept_dt dept_tab,eno number,loc_dt loc_tab);
    create type dept_loc_tb as table of dept_loc_rec1
    create table dept_loc_tb_bk1(dept_dt dept_tab,eno number,loc_dt loc_tab)
    NESTED TABLE dept_dt
    STORE AS dept_tab12,
    NESTED TABLE loc_dt
    STORE AS loc_tab12
    insert into dept_loc_tb_bk1 values(dept_tab(dept12(3,'ABD','LOC')
    ,dept12(4,'ABD','LOC')
    ,dept12(5,'ABD','LOC')),3,loc_tab(loc12(21,'AAB'),
    loc12(22,'AAB'),
    loc12(23,'AAB')));
    when I am trying to fetch data from ref cursor to pl/sql table which i am getting an error ora-06504: pl/sql : Return types of result set variables or query do not match.
    I have created a nested table of same as the nested pl/sql object table dept_loc_tb and i have declared the lv_dept_loc_tb of same dept_loc_tb but getting an above error when trying to fetch into that variable.
    Please any one who can solve my problem.
    declare
    type cr is ref cursor;
    cr_obj cr;
    lv_dept_loc_tb dept_loc_tb;
    begin
    open cr_obj for select dept_dt,eno,loc_dt from dept_loc_tb_bk1;
    fetch cr_obj bulk collect into lv_dept_loc_tb;
    close cr_obj;
    end;

    Your query selects 3 separate columns therefore requires 3 collections of corresponding types. You want to treat those 3 columns as an object of DEPT_LOC_REC1 type:
    SQL> declare
      2  type cr is ref cursor;
      3  cr_obj cr;
      4 
      5  lv_dept_loc_tb dept_loc_tb;
      6 
      7  begin
      8  open cr_obj for select dept_dt,eno,loc_dt from dept_loc_tb_bk1;
      9  fetch cr_obj bulk collect into lv_dept_loc_tb;
    10  close cr_obj;
    11  end;
    12  /
    declare
    ERROR at line 1:
    ORA-06504: PL/SQL: Return types of Result Set variables or query do not match
    ORA-06512: at line 9
    SQL> declare
      2  type cr is ref cursor;
      3  cr_obj cr;
      4 
      5  lv_dept_loc_tb dept_loc_tb;
      6 
      7  begin
      8  open cr_obj for select DEPT_LOC_REC1(dept_dt,eno,loc_dt) from dept_loc_tb_bk1;
      9  fetch cr_obj bulk collect into lv_dept_loc_tb;
    10  close cr_obj;
    11  end;
    12  /
    PL/SQL procedure successfully completed.
    SQL> SY.
    P.S. Discover sys_refcursor.

  • How to create table from ref cursor

    I have a proc that returns a ref cursor, whats the simplest way to create a table based on the return of the ref cursor?
    declare
    type rc is ref cursor;
    p_data rc;
    begin
    call_my_proc(p_data);
    :result := p_data; -- If I run this in TOAD I can see the data here but I want to create a table based on it rather than outputting it)
    end;
    thanks.
    edit: sorry. typed this wrong first time, should be right now

    961469 wrote:
    I have a proc that returns a ref cursor, whats the simplest way to create a table based on the return of the ref cursor?Not to do it...
    A cursor is not a result set. A cursor is not a result set. Worth repeating several times as this is a common misconception
    A cursor is essentially a program. Executable code that was compiled from a SQL source code program.
    A SELECT cursor is "read" program. Each fetch instruction runs this program (from its current "paused state"), and outputs data.
    An INSERT cursor is a "write" program. You pass data to it (process called binding, via bind variables). You then execute the program. It writes the data it received (can be bulk data via a bulk bind) to table.
    Now your question is: How do I write the output of a cursor program back to the database?
    The answer is that a "write" cursor program is needed. Your code needs to execute (fetch output from) the ref (read/select) cursor. Then bind that data to the "write" cursor and execute it.
    In other words, you have a read cursor and a write cursor, and you need to pass data from one to the other.
    HOWEVER.. This is slow. This does not scale. This is also known as slow-by-slow row by row processing.
    The correct approach is to create a single program. One that reads the data, and then writes the data. No to send data via a detour through your code between the read part and write part.
    The cursor to create is an INSERT..SELECT cursor. This can do fast direct path inserts. This can be executed in parallel - i.e. the database executing several copies of this read-and-write program at the same time.

  • How to create a procedure function with a return value of ref cursor?

    Can anybody provide a sample about how to create a procedure function with a return value of REF CURSOR?
    I heard if I can create a function to return a ref cursor, I can use VB to read its recordset.
    Thanks a lot.

    http://osi.oracle.com/~tkyte/ResultSets/index.html

  • Number of total rows returned by a ref cursor without using FETCH

    Hi. How can we get the total number of rows returned by a ref cursor without doing the FETCH? I mean, if you use %ROWCOUNT, it only returns the current row number being returned in every fetch. This is not what I want. My purpose is to determine if my query using ref cursor returns greater than zero total rows without using fetch. Thanks.

    As John pointed out in the thread you linked to, the only way to know how many rows a query will return is to actually fetch all the rows. Oracle doesn't know how many rows a query is going to return until it actually fetches the last row.
    Plus, assuming the default transaction isolation level, if you run the same query multiple times in succession, there is no guarantee that the results will be the same.
    If you just want to know whether a query will return a nonzero number of rows, why not just write the code to assume that it returns at least 1 row and handle the zero row result as an exception.
    Justin

  • Return XML from Ajax

    Hi,
    I need to provide the XML tags and dynamic content from the APEX Ajax routine - to be used for the Fusioncharts. How can I return XML from the Ajax routine.
    Thanks.
    Andy

    Andy,
    Seeing how you are doing everything on load, there is really only a few changes you need to make in order for this to happen via ajax.
    1. Create an ondemand process which generates only XML named GET_CHART_XML. Something like ...
    declare
      l_xml             VARCHAR2 (32767);
      p_region_width    VARCHAR2 (10)    := '700';--------------------------------------
      p_region_height   VARCHAR2 (10)    := '300';-- not sure what these are here for --
      p_chart_debug     VARCHAR2 (10)    := '0';  --------------------------------------
    begin
      l_xml := '<graph showNames=''1'' decimalPrecision=''0''  >' ;
      for d in (select b.proj_phase, count(*) total
                  from it_proj_srvc_req a, it_proj_phase b
                 where a.it_proj_phase_pk = b.it_proj_phase_pk
                   and a.it_proj_phase_pk not in (10,99)
                   and exists (select 'x' from it_proj_srvc_req_pers d,
                                               it_proj_srvc_group e
                                         where d.dph_pers_pk = e.mem_pers_pk
                                           and e.adm_pers_pk = :F120_DPH_PERS_PK
                                           and a.it_proj_srvc_req_pk = d.it_proj_srvc_req_pk)
                                         group by b.proj_phase)
      loop
        if d.proj_phase = 'Current' then
          l_xml := l_xml || '<set name=''' || d.proj_phase || ''' value=''' || d.total || ''' isSliced=''1''/>';
        else
          l_xml := l_xml || '<set name=''' || d.proj_phase || ''' value=''' || d.total || ''' />';
        end if;
      end loop;
      l_xml := l_xml || '</graph>';
      htp.p(l_xml);
    end;2. Put this JavaScript in the HTMLHeader section of your page.
    <script language="JavaScript" src="/i/themes/custom/FusionCharts/FusionChartsFree/JSClass/FusionCharts.js"></script>
    <script type="text/javascript">
      function renderChart(){
        var myChart = new FusionCharts("/i/themes/custom/FusionCharts/FusionChartsFree/Charts/FCF_Pie2D.swf", "ChartId", "250", "100");
        var get = new htmldb_Get(null,$v('pFlowId'),'APPLICATION_PROCESS=GET_CHART_XML',$v('pFlowStepId'));
        get.GetAsync(function(){
          if(p.readyState == 1){
            $x('chartdiv').innerHTML = '<p>Loading Chart...</p>';
          }else if(p.readyState == 4){
            if(!p.responseText){return false;};
            myChart.setDataXML(p.responseText);
            myChart.render("chartdiv");
        get = null;
    </script>3. Lastly create a button with a url target which points to "javascript: renderChart()".
    I was not able to actually test this as I do not have access to the java script dependencies for the flash chart. so I apologize if the JS has a typo in there.
    Hope this gets you started in the right direction.
    Tyson Jouglet

  • Multiple SELECTS returned to a REF CURSOR

    Hi there
    I have a query regarding returning a REF Cursor from multiple selects and any input/hints would be greatly appreciated.
    Basically, I have a select(from multiple tables) that returns a set of rows(query 1) and another (from multiple tables) that returns a set of data that needs to be appended to the results from query 1. Initially my thoughts were to join the queries using an inline view. This returns the correct number of rows but as there is only 1 field I can use to join the queries it is very inefficient and takes forever to execute.
    So, I’ve there for had to rethink my design but have hit a brick wall – so to speak!
    Is it possible to use one cursor for each query and return the results in 1 ref cursor?
    I’m thinking I would need something like the following: -
    Cursor 1 is
    Select a.quote, b.name,c.price from table a,b,c
    Cursor 2 (cursor 1.quote IN)
    Is
    Select * from table d,e,f
    Where d.quote = cursor1.quote
    What I need to output in the ref cursor is as follows: -
    For each record returned from query 1, return the data from query 2.
    Many thanks in advance
    ps I'm using 9i

    Do UNION or UNION ALL work on your version of Oracle? <g>

  • Still not possible (4.0 EA3) to copy displayed column headings from ref cursor output.

    Hi,
    I've created an enhancement request to allow displayed column headings from ref_cursor output to be copied.
    This is still not possible (4.0 EA3)
    The ref cursor data can be copied, but not the headings..
    See July 2012 discussion of problem in comments at
    http://www.thatjeffsmith.com/archive/2011/12/sql-developer-tip-viewing-refcursor-output/

    Hi,
    I think you're out of luck... except if you're on 11g where you can use DBMS_SQL.TO_CURSOR_NUMBER to convert the REF CURSOR to a DBMS_SQL cursor, and then benefit from the DBMS_SQL package to get column details.
    http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28419/d_sql.htm#CHDJDGDG

  • Return XML from MVC WebAPI Web Service

    The tutorials to create a web service using MVC WebAPI (frmaework4.5) in VS 2013  is touted as being "very simple" to return JSON or XML.
    But then, all you get is JSON. When you want to return a plain ole' string of XML ... there is no clear documentation. I see a bunch of posts where people are referencing the ActionResult method ... which is not in the APIController class... so that implies
    to me that I need to roll my own from the Controller class. That doesn't seem right to me.
    So ... how does one return an XML string from an MVC WebApi application?
    * the list of "questions similar to yours" that this forum presents me either:  a) are for ASMX in VS 2008 or b) do not work.
    Any direction to some documentation is appreciated.
    Thanks

    Hi,
    If this issue is related to MVC, you could ask this question in the ASP.NET forum:
    http://forums.asp.net. If then, you could get an answer more quickly and professional. Maybe the
    WCF, ASMX and other Web Services forum will be better for this issue. Thanks for your cooperation.
    Have a nice day,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • Returning XML from CF for xmlHttpRequest

    Greetings,
    Not sure what I'm doing wrong here, but I can't seem to get
    a .cfm page to return the necessary xml for use in my
    xmlHttpRequest javascript code. I know the problem doesn't exist
    within my javascript code......if I build the URL to connect to and
    point it at an actual XML document, all is well.....I get a proper
    XML DOM document back and I can do what I want. However, if I point
    it at a .cfm page that is generating XML, it doesn't work.
    I've tried a few different ways (<cfcontent> etc)of
    trying to get CF to return the results of the .cfm page as XML, but
    it's not working.
    Suggestions?

    Well, there you go. Turns out there's some slightly
    contradictory info in the help for <cfxml>. In the main help
    for the <cfxml> tag, there's no mention of the fact that you
    should not use the standard <?xml version="1.0" etc> xml
    processing directive when you're using that tag. It is, however,
    mentioned on one of the associated help pages. So, now that I've
    removed the directive, all is well.

  • Returning xml from a struts action to be used by a ajax client

    Hello,
    I'm having issues with my ajax call on a WAS server. It functions correctly when run locally on tomcat and WSAD servers.
    It looks like the response isnt comming back when the ajax call is made.
    My java struts action does the following:
            String xml = .....
            aResponse.setContentType("text/xml");            
            aResponse.getWriter().write(xml);
            aResponse.getWriter().flush();
           return null;Is this the correct way to pass back a response?
    do I have to set the header? if so, what should it be?
    Thanks,
    Con.

    A JSP is usually easier to construct the XML since you have looping etc. - otherwise OK.

  • How we can pass the list of variable from ref cursor ??

    pls explain with example

    Simple example:
    SQL> create table t as select level col from dual connect by level <= 10;
    Table created.
    SQL> create or replace procedure myproc
      2    ( p_num_list in sys.odcinumberlist
      3    , p_ref out sys_refcursor
      4    )
      5  as
      6  begin
      7    open p_ref for select col
      8                   from   t
      9                   where  col in (select * from table(p_num_list));
    10  end;
    11  /
    Procedure created.
    SQL> var rc refcursor
    SQL> set autoprint on
    SQL> exec myproc(sys.odcinumberlist(1,2,3), :rc);
    PL/SQL procedure successfully completed.
           COL
             1
             2
             3
    3 rows selected.
    SQL> exec myproc(sys.odcinumberlist(1), :rc);
    PL/SQL procedure successfully completed.
           COL
             1
    1 row selected.
    Search http://asktom.oracle.com for more examples...
    Also, see:
    The Tom Kyte Blog: Varying in lists...

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

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

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

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

Maybe you are looking for