Returning SQL cursor from Stored Procedure

Hi,
I have a query regarding returning sql cursor from stored procedure to java in oracle 11g.
I want to query some data ex: my query returns A, B, C. Also, now I want to query some other data ex: D, E, F. Now I want to return this data as an sql cursor as a single row . Example: A,B,C,D,E,F. Is it possible to return/create a cursor in stored procedure?
assume both query returns equal number of rows.. however both are not related to each other..

RP wrote:
Hi,
I have a query regarding returning sql cursor from stored procedure to java in oracle 11g.
I want to query some data ex: my query returns A, B, C. Also, now I want to query some other data ex: D, E, F. Now I want to return this data as an sql cursor as a single row . Example: A,B,C,D,E,F. Is it possible to return/create a cursor in stored procedure?
assume both query returns equal number of rows.. however both are not related to each other..It sounds like what you need is a ref cursor.
First thing to remember though is that cursors do not hold any data (see: {thread:id=886365})
In it's simplest form you would be creating a procedure along these lines...
SQL> create or replace procedure get_data(p_sql in varchar2, p_rc out sys_refcursor) is
  2  begin
  3    open p_rc for p_sql;
  4  end;
  5  /
Procedure created.
SQL> var rc refcursor;
SQL> exec get_data('select empno, ename, deptno from emp', :rc);
PL/SQL procedure successfully completed.
SQL> print rc;
     EMPNO ENAME          DEPTNO
      7369 SMITH              20
      7499 ALLEN              30
      7521 WARD               30
      7566 JONES              20
      7654 MARTIN             30
      7698 BLAKE              30
      7782 CLARK              10
      7788 SCOTT              20
      7839 KING               10
      7844 TURNER             30
      7876 ADAMS              20
      7900 JAMES              30
      7902 FORD               20
      7934 MILLER             10
14 rows selected.
SQL> exec get_data('select deptno, dname from dept', :rc);
PL/SQL procedure successfully completed.
SQL> print rc
    DEPTNO DNAME
        10 ACCOUNTING
        20 RESEARCH
        30 SALES
        40 OPERATIONS
        50 IT SUPPORTWhich takes an SQL statement (as you said that both your queries were unrelated), and returns a ref cursor, and then your Java code would fetch the data using that cursor.
Now, as for getting your rows to columns and combining two queries that do that... something along these lines...
SQL> select * from x;
C
A
B
C
SQL> select * from y;
C
D
E
F
SQL> ed
Wrote file afiedt.buf
  1  select x.col1, x.col2, x.col3
  2        ,y.col1 as col4
  3        ,y.col2 as col5
  4        ,y.col3 as col6
  5  from (
  6        select max(decode(rn,1,col1)) as col1
  7              ,max(decode(rn,2,col1)) as col2
  8              ,max(decode(rn,3,col1)) as col3
  9        from (select col1, rownum rn from (select * from x order by col1))
10       ) x
11  cross join
12       (
13        select max(decode(rn,1,col1)) as col1
14              ,max(decode(rn,2,col1)) as col2
15              ,max(decode(rn,3,col1)) as col3
16        from (select col1, rownum rn from (select * from y order by col1))
17*      ) y
SQL> /
C C C C C C
A B C D E F... will do what you ask. For further information about turning rows to columns read the FAQ: {message:id=9360005}

Similar Messages

  • OCI8: returning cursors from stored procedures

    The short version of my question is:
    In OCI8, how do open a cursor from the database stored procedure, return it to my C++ program and fetch from it, given that in OCI8 cursors and cursor functions are becoming obsoleted?
    The long version of the same question is:
    I am converting my C++ code from the Oracle 7.3 OCI driver to the Oracle8 OCI driver. One thing I did very frequently in Oracle 7.3 OCI code is open a multi-row select cursor within a stored procedure and return that cursor to my program. In the program, I would then do the fetching with the returned cursor. This was very useful, as it allows me to change the queries in the stored procedure (for example, to append information to certain columns or make some data in all uppercase) without recompiling the application due to a changed SQL string.
    My 7.3 psuedocode is as follows:
    stored procedure def:
    TYPE refCurTyp IS REF CURSOR;
    FUNCTION LoadEmployeeData RETURN refCurTyp;
    stored procedure body:
    FUNCTION LoadEmployeeData RETURN refCurTyp IS
    aCur refCurTyp;
    BEGIN
    OPEN aCur FOR
    SELECT emp_id, emp_name
    FROM employee_table
    ORDER BY emp_name;
    return aCur;
    END;
    OCI code: // all functions are simplified, not actual parameter listing
    // declare main cursor variable #1 and return cursor variable #2
    Cda_Def m_CDAstmt, m_CDAfunction;
    // open both cursors
    oopen(m_CDAstmt, ...);
    oopen(m_CDAfunction, ...);
    // bind cursor variable to cursor #2
    oparse(&m_CDAstmt, "BEGIN :CUR := MYPACKAGE.LoadEmployeeData; END;");
    obindps(&m_CDAstmt, SQLT_CUR, ":CUR", &m_CDAfunction);
    // run cursor #1
    oexn(&m_CDAstmt);
    // bind variables from cursor #2, and fetch
    odefineps(&m_CDAfunction, 1, SQLT_INT, &m_iEmpId);
    odefineps(&m_CDAfunction, 2, SQLT_CHAR, &m_pEmpName);
    while (!ofen(&m_CDAfunction))
    // loop: do something with fetch
    // values placed in m_iEmpID and m_pEmpName
    This works perfectly, and has really helped to make my code more maintainable. Problem is, in Oracle 8 OCI both cursors and the cursor functions (such as oopen()) are becoming obsoleted. Now it uses statement and environment handles. I know I can still use Cda_Def and cursors--for a while--within OCI8, but I need to know the official up-to-date method of returning a cursor from the database and fetching within my C++ code. Any code fragment, or explanation of what I need to do in OCI8 would be appreciated (perhaps I need to bind to a statement handle instead? But the stored procedure still returns a cursor.)
    The Oracle8 OCI has a new SQLT_ type, SQLT_RSET, which the header file defines as "result set type". Unfortunately, it's almost completely undocumented in the official documentation. Am I supposed to use this instead of the obsolete SQLT_CUR?
    Thanks,
    Glen Mazza

    Email me diorectly and I will get you some code that might help. I fail to see the relevance of posting this type of information in the JDeveloper forum.

  • URGENT : Return Bulk data from Stored Procedure

    Hi,
    Tell me, how do I return a bulk of data which
    does not exist in the data base
    but is concluded while the Stored Procedure is executed
    from the Stored procedure
    to the C++ program.
    For Example:
    Table ABC
    Field1 Field2 Field3
    A 1 3
    B 1 5
    C 2 10
    Table DEF
    Field1 Field2 Field3
    D 10 24
    E 3 16
    F 8 19
    SP_TESTING
    Depending on the values in both the tables
    for some range of conditions,
    a conclusion X is derived for each range value of the
    condition range.
    Now I need to return this bulk of data X with the
    condition they belong to
    back to the C++ code calling it....
    NOTE : A stored procedure is requited as there is a lot
    of processing
    required before we conclude the result X for each value
    in the condition range.
    If I execute this code from C++ instead of Stored
    procedure
    it is very slow and speed is a prime requirement of my
    system.
    Also i'm not using any MFC class to access database.
    I'm using ConnectionPtr, RecordsetPtr and _CommandPtr
    from msado15.dll for database access...
    One solution to this could be use of Temp tables.
    As this process is used by a lot of different stored
    procedures having a common
    temp table to all will need something like 50 NUMERIC
    fields, 50 VARCHAR fields
    and so on, which doesn't seem like a very good solution
    to this problem.
    Sounds like something I would have done while in school,
    implement a dumb solution.
    So, please suggest me a solution as to how do I return
    bulk data in the form
    of recordsets from stored procedure.
    Regards
    Shruti

    Use Out parameter mode
    SQL> CREATE OR REPLACE procedure a1 (x  OUT NUMBER, y  OUT NUMBER) AS
      2  BEGIN
      3        x:= 1;
      4        y:= 2;
      5  END;
      6  .
    SQL> /
    Procedure created.
    SQL> SET SERVEROUTPUT ON
    SQL> DECLARE
      2   a NUMBER :=3;
      3   b NUMBER :=4;
      4  BEGIN
      5   a1 (a,b);
      6      DBMS_OUTPUT.PUT_LINE( 'a = ' || a );
      7      dbms_output.put_line( 'b = ' || b );
      8  END;
      9  .
    SQL> /
    a = 1
    b = 2
    PL/SQL procedure successfully completed.By default parameters are copied to the OUT parameter mode .
    COPY hint in PLSQL don’t send a pointer to calling program unit but NOCOPY
    does.
    Khurram

  • Return multiple cursors from one procedure

    Hi,
    I have a stored procedure that is suposed to return multiple records. I know that for each table that I return I have to add a param to the stored procedure, param with ref cursor type.
    I do not know exactly how many tables I have to return, it depends on data from some tables.
    Is it possible to return an unknown number of tables? like an array or something ...
    Please help

    In order to keep it transparent to the developer, I have to translate exactly the stored procedures from SQL Server to Oracle.Well "exactly" is not something that you are going to achieve. You're talking about two disperate languages. That's like saying you want to translate French to English, but it must stay French.
    You obviously want to mimick the existing functionality, but in some cases you're just going to have to bite the bullet and accept that you won't be able to do it totally transparently. In this case, the developers are going to have to make some changes at their end of things too.
    To translate the procedures from T-SQL to Oracle was
    the easiest and most convenient option to the
    developers, so they will not have to write different
    code for Oracle and SQL.But they will. Anyone who evaluated the project and determined that the developers wouldn't need to do anything when moving from one platform to another should be sacked for incompetence.
    ;)

  • Reports 3.0, Ref Cursor from stored procedure

    I have a problem trying to use Ref Cursor as datasource (i.e.
    Ref Cursor Query) in Reports 3.0
    I have created a stored package with a function which returns
    Ref Cursor.
    That function just opens the cursor and returns it to the
    calling module.
    Reports recognizes returned cursor - it creates a group for that
    query, with all columns, than I built
    a layout model - everything is OK on that stage.
    During the execution of that report (from previewer or using
    Reports Runtime) I got an error message like that:
    REP-0065 Virtual Memory System Error
    REP-0200 Cannot allocate enough memory cavaa22
    Error's description does not correspond the reality :) - there
    is enough virtual & physical memory according to
    Task Manager information.
    So, that does not work when this package is stored one.
    When I create the package on the client side - in Reports -
    everything works just fine.
    Cursor is opened with a very simple query, selecting records
    from the very simple table having only one record.
    There is no code written which closes that cursor or fetches the
    records.
    Client platform: WinNT 4.0 SP3
    Oracle Reports: 3.0.5.8.0
    Oracle Server: Oracle8 8.0.5.0.0 (and I tried also on Oracle7
    7.3.4.3.0)
    Thanx.
    null

    Sara,
    GTT (Global Temporary Tables) in Oracle work a different way compared to SQL Server and Informix. There you can create temporary tables on the fly and drop them on the fly.
    Here you should (note, you don't have to, but, best practice says that you should) create the table using the syntax...
    create global temporary table.....
    Once you create it, even though it looks like persistent table, it's not. It will have it's own individual data PER SESSION . You have two types of GTTs:
    ON COMMIT PRESERVE ROWS and ON COMMIT DELETE ROWS (they work in slightly different way).
    Look up GTTs here:
    http://download-east.oracle.com/docs/cd/B19306_01/server.102/b14231/tables.htm#sthref2213
    HTH,
    Rahul

  • Launch the SQL*Loader From Stored Procedure???

    Is it possible to aaunch the SQL*Loader from a stored procedure? Please help!

    Try the documentation on external procedures

  • File Ownership while executing sql script from stored procedure

    We have a test_command.sql script which is spooling the result into a file. From database we have one Store Procedure(run_sql) which is
    calling and executing the .sql script.
    When we are calling the sql script directly from the database, i e SQL > @/dccops/test_command.sql it is creating the
    file under the Ownership of OS user which is connected to the system.
    The problem we are facing is when we are executing the stored procedure i e exec run_sql(), the file is creating under
    Oracle User.
    Could u please suggest me a solution inorder to create the output file under the user who is logged to the OS.

    First of all, your usage of IM speak is NOT appreciated. Please do not address anyone as if they were a 12-year old.
    'Our Applcation is in C. So we have to call the procedure to run the sql script.'
    This is just utter nonsense!
    Oracle has Pro*C which allows Embedded SQL in C. There is also OCI (Oracle Call Interface) to call Oracle directly in C, and there is OCCI, to do the same in C++.
    Apart from that, Oracle has Ole DB for Windows platforms, to allow for a .NET compatible interface to Oracle.
    There is NO NEED AT ALL to call PL/SQL to run a SQL script.
    Sybrand Bakker
    Senior Oracle DBA

  • Running a sql script from stored procedure

    Hi everyone!
    Has anybody tell me how to execute a sql script from a stored
    procedure!
    Thanks in advance!
    Sasa

    >
    Hi everyone!
    Has anybody tell me how to execute a .sql file from a stored
    procedure!
    Thanks in advance!
    Sasa Sorry, a .sql file!!

  • Conversion failed when converting the nvarchar value to data type int when returning nvarchar(max) from stored procedure

    Thank you for your help!!! 
    I've created a stored procedure to return results as xml.  I'm having trouble figuring out why I'm getting the error message "Conversion failed when converting the nvarchar value '<tr>.....'
    to data type int.    It seems like the system doesn't know that I'm returning a string... Or, I'm doing something that I just don't see.
    ALTER PROCEDURE [dbo].[p_getTestResults]
    @xml NVARCHAR(MAX) OUTPUT
    AS
    BEGIN
    CREATE TABLE #Temp
    [TestNameId] int,
    [MaxTestDate] [DateTime],
    [Name] [nvarchar](50),
    [Duration] [varchar](10)
    DECLARE @body NVARCHAR(MAX)
    ;WITH T1 AS
    SELECT DISTINCT
    Test.TestNameId
    , replace(str(Test.TotalTime/3600,len(ltrim(Test.TotalTime/3600))+abs(sign(Test.TotalTime/359999)-1)) + ':' + str((Test.TotalTime/60)%60,2)+':' + str(Test.TotalTime%60,2),' ','0') as Duration
    ,MaxTestDate = MAX(TestDate) OVER (PARTITION BY TM.TestNameId)
    ,TestDate
    ,TM.Name
    ,Test.TotalTime
    ,RowId = ROW_NUMBER() OVER
    PARTITION BY
    TM.TestNameId
    ORDER BY
    TestDate DESC
    FROM
    Test
    inner join TestName TM on Test.TestNameID = TM.TestNameID
    where not Test.TestNameID in (24,25,26,27)
    INSERT INTO #Temp
    SELECT
    T1.TestNameId
    ,T1.MaxTestDate
    ,T1.[Name]
    ,T1.Duration
    FROM
    T1
    WHERE
    T1.RowId = 1
    ORDER BY
    T1.TestNameId
    SET @body ='<html><body><H3>TEST RESULTS INFO</H3>
    <table border = 1>
    <tr>
    <th> TestNameId </th> <th> MaxTestDate </th> <th> Name </th> <th> Duration </th></tr>'
    SET @xml = CAST((
    SELECT CAST(TestNameId AS NVARCHAR(4)) as 'td'
    , CAST([MaxTestDate] AS NVARCHAR(11)) AS 'td'
    , [Name] AS 'td'
    , CAST([Duration] AS NVARCHAR(10)) AS 'td'
    FROM #Temp
    ORDER BY TestNameId
    FOR XML PATH('tr'), ELEMENTS ) AS NVARCHAR(MAX))
    SET @body = @body + @xml +'</table></body></html>'
    DROP TABLE #Temp
    RETURN @xml
    END
    closl

    Your dont need RETURN inside SP as you've declared @xml already as an OUTPUT parameter. Also you can RETURN only integer values using RETURN statement inside stored procedure as that's default return type of SP.
    so just remove RETURN statement and it would work fine
    To retrieve value outside you need to invoke it as below
    DECLARE @ret nvarchar(max)
    EXEC dbo.[P_gettestresults] @ret OUT
    SELECT @ret
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • What is the best approach to return Large data from Stored Procedure ?

    no answers to my original post, maybe better luck this time, thanks!
    We have a stored proc (Oracle 8i) that:
    1) receives some parameters.
    2)performs computations which create a large block of data
    3) return this data to caller.
    compatible with both ASP (using MSDAORA.Oracle), and ColdFusion (using Oracle ODBC driver). This procedure is critical in terms of performance.
    I have written this procedure as having an OUT param which is a REF CURSOR to a record containing a LONG. In order to make this work, at the end of the procedure I have to store the working buffer (an internal LONG variable) into a temp table, and then open the cursor as a SELECT from the temp table.
    I have tried to open the cursor as a SELECT of the working buffer (from dual) but I get the error "ORA-01460: unimplemented or unreasonable conversion requested"
    I suspect this is taking too much time; any tips about the best approach here? is there a resource with REAL examples on returning large data?
    If I switch to CLOB, will it speed the process, be compatible with callers, etc ? all references to CLOB I saw use trivial examples.
    Thanks for any help,
    Yoram Ayalon

    Create a new farm in the secondary Data Center at the same patch level with the desired configuration. Replicate the databases using the method of choice (Mirroring, AlwaysOn, etc.). Create a downtime window where you can then attach the databases to the
    new farm's Web Application(s)/Service Application(s).
    Trevor Seward
    Follow or contact me at...
    &nbsp&nbsp
    This post is my own opinion and does not necessarily reflect the opinion or view of Microsoft, its employees, or other MVPs.

  • SSRS 2008 not returning correct dataset from Stored Procedure

    Hi,
    I have a stored proc which returns different no. of columns as output based on the input parameter. The issue I am facing is that the SSRS 2008 is always populating the column list of the dataset with the first select list irrespective of the input
    parameter.
    How can I have the SSRS populate the column list based on the input parameter I am passing?
    eg.
    IF @type
    =
    'test'
    BEGIN
    SELECT 1 AS Col1,2 AS Col2
    END
    ELSE
    IF @type
    =
    'test1'
    BEGIN
    SELECT 1 AS Col1,2 AS Col2,3 AS Col3
    END
    SSRS always populates the dataset with two columns  viz col1 & col2 even when I pass
    'test1' as input parameter.
    Thanks for the help in advance.
    Sherin

    From my experiences, your dataset must return the same number of column and same name in both select statement.
     IF
    @type =
    'test'
    BEGIN
    SELECT 1 AS Col1,2 AS Col2,
    null AS Col3
    END
     ELSE
    IF @type
    =
    'test1' 
    BEGIN 
    SELECT 1 AS Col1,2 AS Col2,3 AS Col3
    END

  • Returning rowcount and resultset from stored procedure

    Hello,
    In SQL Server you can return multiple resultsets from stored procedure by simple SELECT statement. But in Oracle, you have to use SYS_REFCURSOR.
    Sample code:
    CREATE OR REPLACE PROCEDURE sp_resultset_test IS
    t_recordset OUT SYS_REFCURSOR
    BEGIN
    OPEN t_recordset FOR
    SELECT * FROM EMPLOYEE;
    END sp_resultset_test;
    Is there any other way in Oracle 10 or 11 ?
    Thank You.

    What is the requirement? Oracle is far more flexible than SQL-Server... with numerous features that do not exist in SQL-Server. (Fact)
    One of the biggest mistakes you can make is to treat Oracle like SQL-Server... trying to match feature A1 in SQL-Server to feature B3 in Oracle.
    Does not work that way.. rather then stick to SQL-Server as SQL-Server does SQL-Server specific features far better than Oracle.
    So instead of trying to map what a T-SQL stored proc to do to an Oracle ref cursor (even to the extent of using that very silly sp_ prefix to name the proc), tell us the problem and requirements... That way we can tell you what Oracle features and options are best used to solve that problem - instead of competing in some unknown feature comparison event with SQL-Server.

  • Ora-06550 returning data from Stored Procedure and Entity Data Model

    Hi.
    I'm creating an application that uses a WCF Service to return data. I also created a proyect with the EDMX design and mapped most of my DBModel to a classes context. I have added some of the procedures as well. One of them receive some parameters and return a Sys_RefCursor, that is populated according to the parameters.
    I have declared the "<add >" tags in the Web.Config and imported the function of the Procedure. When I call the Asyncronous function I get different exceptions:
    1. If I call the function, with all of the parameters i get:
    Oracle.DataAccess.Client.OracleException: ORA-06550: línea 1, columna 8:
    PLS-00306: número o tipos de argumentos erróneos al llamar a
    'SP_HECHOSJURITER'
    ORA-06550: línea 1, columna 8:
    (wrong number or types of arguments in call to 'SP_HECHOSJURITER')
    2. If i just set 1 parameter in the SP, returning the same type of data, I get:
    Error al recibir la respuesta HTTP a
    http://localhost/Procalculo.CGFM.SIGOC.DatosServices/ServiceDatos.svc.
    (failed to receive http response. error 12152)
    3. If I don't set any parameters in the procedure, it works fine, and return correct data.
    It exclusively happen with one entity.
    Any clue?
    I appreciate any help.

    When you return result sets from stored procedures to Entity Framework, you are very likely using implicit result sets. Implicit result sets don't need to be declared as a parameter in code, only in the <add> tags to define the metadata in the .NET config file.
    For example, in the EF Oracle By Example, you'll see that the stored procedure in the function import has three parameters, but only two are declared in the code. The third one was defined in the config file.
    http://download.oracle.com/oll/obe/EntityFrameworkOBE/EntityFrameworkOBE.htm

  • How to execute .sql file in Stored Procedure?

    Hi,
    I have an urgent requirement, where i have to execute .sql file form Stored Procedure.
    This .sql file will have set of update statement. I need to pass value to this update statement.
    Kindly please help me.
    Regards,
    Irfan

    This is required as part of Data Migration where  i have to do 100 of table's update. Each time update table will defer, so its better to have in separate script file (.sql). Can u paste some sample/syntax to exceute .sql file from stored procedure. I am new to this PL/SQL.
    How have you determined that it's "better" to have seperate scripts?  I assume you mean the table name will "differ" (and not "defer" - I assume that's just because English isn't your first language? no problem - I think I understand what you're asking).
    So what I think you're asking is that you have dynamic table names but each table needs to be updated in the same way?
    Question: Why do you have tables with different names that all need the same process doing to them?
    Assuming it's a valid requirement (and 99% of the time doing dynamic coding implies it's not).... you could use dynamic code, rather than 'scripts'...
    e.g.
    create procedure update_table(tbl_name varchar2) is
    begin
      execute immediate 'update '||tbl_name||' set lastupdate = null';
    end;
    As you haven't bothered to provide a database version, any example code/data or explanation of what you're actually doing, you're not going to get any detailed answer.  Please do take the time to read the FAQ and post appropriate details so people can help you.

  • Return a parameter through stored procedures

    Hello Experts
    I want to return parameter through stored procedures so as to ensure that the application has been executed properly.
    My source message format is
    <StatementName5>
    <storedProcedureName action=u201D EXECUTEu201D>
      <table>Summarize_prc</table>
    <empid  [isInput=u201Dtrueu201D] [isOutput=true] type=SQLDatatype>val1</empid>
    </storedProcedureName > 
    </StatementName5>
    Do i need to put some extra parameters for return values from the stored procedures?
    What would be the response message format to return the parameters from stored procedure.
    Thanks
    Sabyasachi

    Hi,
    If you wants to read the return values from stored procedure, the scanario should be designed as Sync.
    The format looks like thsi
    <Message Type Name>
          <STATEMENTNAME_response>
                      <Field1> </Field1>
       </STATEMENTNAME_response>
    </Message Type Name>

Maybe you are looking for