Result Sets from Stored procedures in Oracle

Source: Internet
Author: User
Tags cursor library include connect odbc variables prepare printf strlen
Oracle

Result Sets from Stored procedures in Oracle
A Frequently asked question is:

I ' d like to know whether ORACLE supports procedures (functions) which
Returns result sets.

The answer is most definitely yes. In short, it ' ll look like this:

Create or Replace function sp_listemp return Types.cursortype
As
L_cursor Types.cursortype;
Begin
Open l_cursor for select ename, empno from emp order by ename;
return l_cursor;
End
/
With 7.2 on the "database" you have cursor variables. Cursor variables are cursors opened by a pl/sql routine and fetched from through another application or pl/sql (in 7.3 Pl/sql routines can fetch from cursor variables as OK as open them). The cursor variables are opened with the privelegs of the owner of the procedure and behave just like they were Contained within the Pl/sql routine. It uses the inputs to decide what database it would run a query on.

This is example:

Create or Replace package types
As
Type CursorType is REF CURSOR;
End
/Create or Replace function sp_listemp return Types.cursortype
As
L_cursor Types.cursortype;
Begin
Open l_cursor for select ename, empno from emp order by ename; return l_cursor;
End
/
Examples for Sqlplus, Pro*c, Java/jdbc, ODBC, ado/asp, DBI Perl and OCI follow:
REM Sql*plus commands to use a cursor variable variable c refcursor
EXEC:C: = Sp_listemp
Print C

And the pro*c to use this would look like:
static void Process ()
{
EXEC SQL BEGIN DECLARE section;
Sql_cursor My_cursor;
VARCHAR ename[40];
int empno;
EXEC SQL end DECLARE section;     EXEC SQL whenever SQLERROR do Sqlerror_hard ();     EXEC SQL Allocate:my_cursor; EXEC SQL EXECUTE BEGIN
: my_cursor: = sp_listemp;
End;     End-exec; for (;;)
{
EXEC SQL whenever NotFound do break;
EXEC SQL fetch:my_cursor into:ename, empno; printf ("'%.*s ',%d\n", Ename.len, Ename.arr, empno);
}
EXEC SQL Close:my_cursor;
}
And the Java to could is:

Import java.sql.*;
Import java.io.*;
Import oracle.jdbc.driver.*;
Class Curvar
{
public static void Main (String args [])
Throws SQLException, ClassNotFoundException
{
String Driver_class = "Oracle.jdbc.driver.OracleDriver";
String connect_string = "Jdbc:oracle:thin: @slackdog: 1521:oracle8"; String query = "Begin:1: = sp_listemp; end; ";
Connection Conn; Class.forName (Driver_class);
conn = Drivermanager.getconnection (connect_string, "Scott", "Tiger"); CallableStatement cstmt = conn.preparecall (query);
Cstmt.registeroutparameter (1,oracletypes.cursor);
Cstmt.execute ();
ResultSet RSet = (ResultSet) cstmt.getobject (1); while (Rset.next ())
System.out.println (rset.getstring (1));
Cstmt.close ();
}
}



The following is marktoml@hotmail.com (Mark Tomlinson).


If you have the use of ODBC here are a working example, but it requires the use of the
8.0.5.2.0 or later Oracle ODBC driver, and an 8.0.5 server.
'
' 1 ' Create a form with 1-Text control (TEXT1) and 1-List control (LIST1) and
' 1 Button (Btnexecute).
' 2 ' The only code so you need are a Click on the Your button. This is the Code.
'
'
Private Sub Btnexecute_click ()
' Pl/sql Code
'===========
'
' CREATE OR REPLACE package reftest as
' Cursor C1 is select ename from EMP;
' Type empcur is REF CURSOR return c1%rowtype;
' Procedure getempdata (en in varchar2,empcursor, out empcur);
' End;
'
'
' CREATE OR REPLACE package Body reftest as
' Procedure Getempdata
' (En in varchar2,empcursor an out empcur) is
' Begin
' Open empcursor for select ename from emp where ename like en;
' End;
' End;
'
Dim cn as New rdoconnection
Dim QD as Rdoquery
Dim RS as Rdoresultset
Dim CL as Rdocolumn
Static Number as Integer list1.clear
Number = 0
cn. Connect = "Uid=scott; Pwd=tiger; Dsn=mslangorl; "
' Enable the MS Cursor Library
cn. Cursordriver = Rduseodbc
' Make the connection
cn.      Establishconnection rdnodriverprompt sSQL = "{call Reftest.getempdata (?,?)}" Set QD = CN. CreateQuery ("", sSQL) qd.rdoparameters (0). Type = Rdtypevarchar
QD (0). Direction = Rdparaminputoutput
QD (0). Value = Text1.Text
Qd.rdoparameters (1). Type = Rdtypevarchar ' Dynamic or keyset is meaningless here
Set rs = qd. OpenResultset (rdopenstatic) do
Debug.Print
Debug.Print do Until Rs. Eof
For all CL in Rs.rdocolumns
If IsNull (CL. Value) Then
List1.AddItem "(null)"
' Debug.Print '; Cl. Name; "NULL"; Error Trap for
Null fields
Else
List1.AddItem CL. Value
' Debug.Print '; Cl. Name; " "; Cl. Value;
End If
Next
Debug.Print
Rs. MoveNext
Loop
Loop while Rs. MoreResults
cn. Close End Sub

And now, for a full ASP example (to Jim Hoien and John Durst)

<%@ language=vbscript%><!--#INCLUDE virtual= "/adovbs. INC "--><% ' This demonstration draws heavily from the information contained in the article at ' Http://govt.us.oracle . com/~tkyte/resultsets/index.html ' with special attention to the details of provided by Mark Tomlinson. ' Make sure your have the correct Oracle ODBC driver so it'll support Ref Cursors. ' This demonstration is a joint project by Jim Hoien (jhoien@yahoo.com) and John Durst (jpdurst@yahoo.com) "These are the Statements used on the Oracle server: '/*************************************************************************** /* Create the EMP demo table and populate. (Extracted from Oracle ' s provided demobld.sql) * */**************************************************************** /' CREATE TABLE EMP ' (EMPNO number (4) Not NULL, ' ename VARCHAR2 (Ten), ' JOB VARCHAR2 (9), ' MGR NU Mber (4), ' HireDate DATE, ' SAL number (7,2), ' COMM number (7,2), ' DEPTNO number (2)); ' ' InserT into EMP VALUES ' (7369, ' SMITH ', ' clerk ', 7902, ' 17-dec-80 ', 800,null,20); ' INSERT into EMP VALUES ' (7499, ' ALLEN ', ' salesman ', 7698, ' 20-feb-81 ', 1600,300,30); ' INSERT into EMP VALUES ' (7521, ' WARD ', ' salesman ', 7698, ' 22-feb-81 ', 1250,500,30); ' INSERT into EMP VALUES ' (7566, ' JONES ', ' MANAGER ', 7839, ' 2-apr-81 ', 2975,null,20); ' INSERT into EMP VALUES ' (7654, ' MARTIN ', ' salesman ', 7698, ' 28-sep-81 ', 1250,1400,30); ' INSERT into EMP VALUES ' (7698, ' BLAKE ', ' MANAGER ', 7839, ' 1-may-81 ', 2850,null,30); ' INSERT into EMP VALUES ' (7782, ' CLARK ', ' MANAGER ', 7839, ' 9-jun-81 ', 2450,null,10); ' INSERT into EMP VALUES ' (7788, ' SCOTT ', ' ANALYST ', 7566, ' 09-dec-82 ', 3000,null,20); ' INSERT into EMP VALUES ' (7839, ' KING ', ' PRESIDENT ', NULL, ' 17-nov-81 ', 5000,null,10); ' INSERT into EMP VALUES ' (7844, ' TURNER ', ' salesman ', 7698, ' 8-sep-81 ', 1500,0,30); ' INSERT into EMP VALUES ' (7876, ' ADAMS ', ' clerk ', 7788, ' 12-jan-83 ', 1100,null,20); ' INSERT into EMP VALUES ' (7900, ' JAMES ', ' clerk ', 7698, ' 3-dec-81 ', 950,null,30); ' INSERT into EMP VALUES ' (7902, ' FORD ', ' ANALYST', 7566, ' 3-dec-81 ', 3000,null,20); INSERT into EMP VALUES ' (7934, ' MILLER ', ' clerk ', 7782, ' 23-jan-82 ', 1300,null,10); '/********************************* /* Create A packaged procedure that accepts a department Number and returns the employees. * * * [note:a Standalone procedure won't work, it must be A packaged procedure!] */'/*******************************************************************************************/' CREATE OR REPLACE ' PACKAGE DEPARTMENT as ' TYPE cursor_type is REF CURSOR; ' PROCEDURE Get_emps (I_deptno in number, ' O_result_set out Cursor_type '); end; '/' CREATE OR REPLACE ' PACKAGE body DEPARTMENT as ' PROCEDURE get_emps (i_deptno in number, ' O_result_set out cursor_t ype) ' as ' BEGIN ' OPEN o_result_set for ' SELECT EMPNO, ename ' from EMP ' WHERE DEPTNO = I_deptno; ' End; ' End; '/%>
And the following DBI Perl example is-q_richard_chen@yahoo.com (Richard Chen):

Hello Tom, I am looking for such compilation of Tipson the topic. I did not find the section about Doingit using the popular Perl DBI. After some fiddling iget it working there too. This is a complete workingexample following your model using Perl DBI. I Thinkit is a good idea which you include this in your howtoso, more people would benefit from it. Thanksrichard chen$ cat Demo.pl#!/usr/local/bin/perl-wuse strict;use dbi;use dbd::oracle (: QW); my $dbh = Ora_types T;connect (' dbi:oracle: ', ' Scott ', ' tiger ') or Die $DBI:: errstr;my $sth 1 = $dbh->prepare (q{create or replace package Types as type CursorType is ref cursor;end;}); $sth 1->execute;> > $sth 1 = $dbh->prepare (q{create or Replace function sp_listemp return types.cursortypeas L_ Cursor Types.cursortype;begin open l_cursor for select ename, empno from emp order by ename; return l_cursor;end;}); $sth 1->execute; $sth 1 = $dbh->prepare (q{begin:cursor: = Sp_listemp; End;}); My $sth 2; $sth 1->bind_param_inout (": Cursor", \ $sth 2, 0, {ora_type => ora_rset}); $sth 1->execute () while (my @row = $sth 2->fetchrow_array) {print join (" | ", @row)," \ n "; }


MFC + ODBC VERSION (example checked by Marcin Buchwald) marcin.buchwald@gazeta.pl Oracle server side code are just like in The VB example
CDatabase m_db; BOOL OK = m_db. OpenEx (_t ("DSN=ORCL; Uid=velvet "), CDatabase::useCursorLib); Coraset set (&m_db); set.m_value = Text1.text;set. Open (); while (!set). IsEOF ()) {//Set members contain the values of single row//the IT Hereset. MoveNext ();} Set. Close (); Wherecoraset::coraset (cdatabase* pdb): CRecordset (pdb) {m_nparams = 1;m_nfields =; m_ndefaulttype = snapshot;} CString Coraset::getdefaultsql () {return _t (' {call Reftest.getempdata (?,?)} ');}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.