Result Sets from Stored Procedures In Oracle (轉)

gugu99發表於2007-10-14
Result Sets from Stored Procedures In Oracle (轉)[@more@]

Result Sets from Stored Procedures In

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 ename, empno from emp order by ename;
  return l_cursor;
end;
/

With 7.2 on up of the database you have cursor variables.  Cursor variables are cursors opened by a routine and fetched from by another application or pl/sql routine (in 7.3 pl/sql routines can fetch from cursor variables as well as open them). The cursor variables are opened with the privelegs of the owner of the procedure and behave just like they were completely contained within the pl/sql routine. It uses the inputs to dec what database it will run a query on.

Here is an 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, /JC, ODBC, ADO/, DBI 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', %dn", ename.len, ename.arr, empno );
  }
  EXEC SQL CLOSE :my_cursor;
}

And the java to use this could be:
 

import java.sql.*;
import java.io.*;
import oracle...*;
 
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, "tt", "tiger");
  CallableStatement cstmt = conn.prepareCall(query);
  cstmt.registerOutParameter(1,OracleTypes.CURSOR);
  cstmt.execute();
  ResultSet rset = (ResultSet)cstmt.get(1);
  while (rset.next ())
  System.out.println( rset.getString (1) );
  cstmt.close();
  }
}


 

The following is thanks to marktoml@hot.(mark tomlinson)..
 

If you use ODBC here is 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 fowith 1 Text control (Text1) and 1 List Control (List1) and
'  1 Button (btnExecute).
' 2) The only code that you need is a Click method on your button. Here 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 in out empCur);
'END;
'
'
'CREATE OR REPLACE package body reftest as
'  Procedure GetEmpData
'(en in varchar2,EmpCursor in 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
  De.Print
  Debug.Print
  Do Until rs.EOF
  For Each 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
  L
  Loop While rs.MoreResults
  cn.Close
End Sub


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

<!--#INCLUDE VIRTUAL="/ADOVBS.INC" --&gt

Oracle ADO Test

Test of ADO and Oracle Stored Procedures using Ref Cursors

;UID=;PWD=" objConn.Open connString Set cmdStoredProc = Server.CreateObject ("ADODB.Command") Set cmdStoredProc.ActiveConnection = objConn cmdStoredProc.CommandText = "Department.Get_Emps" cmdStoredProc.CommandType = adCmdStoredProc Set param1 = cmdStoredProc.CreateParameter ("Dept_ID", adInteger, adParamInput) cmdStoredProc.Parameters.Append param1 param1.Value = testDeptNo Set rs = cmdStoredProc.Execute Response.Write ("

Employees in Department # " & testDeptNo & "

" & vbCrLf) Response.Write ("

" & vbCrLf) Response.Write ("

" & vbCrLf) Response.Write (" " & vbCrLf) Response.Write (" " & vbCrLf) Response.Write (" " & vbCrLf) Response.Write (" " & vbCrLf) While (Not rs.EOF) Response.Write (" " & vbCrLf) Response.Write (" " & vbCrLf) Response.Write (" " & vbCrLf) Response.Write (" " & vbCrLf) rs.MoveNext Wend Response.Write ("
Emp #Name
" & rs (0) & "" & rs (1) & "
" & vbCrLf) rs.Close objConn.Close Set rs = nothing Set param1 = nothing Set cmdStoredProc = nothing Set objConn = nothing %>

And the following is thanks to Brett Rosen :

I noticed that you didn't have an OCI entry on ~tkyte/ResultSets/index.html . Here is OCI code to do this (Oracle 81) if you want to include it on that page. Some error checking and cleanup has been removed, but the below should work. (once dbname has been replaced appropriately) Brett int main(int argc, char* argv[]) { OCIError* pOciError; char* pConnectChar = "dbname"; char* pUsernameChar = "scott"; char* pPasswordChar = "tiger"; int answer; OCIStmt* pOciStatement; char* sqlCharArray = "BEGIN :success := sp_ListEmp; END;"; int id; char ename[40]; OCIEnv* g_pOciEnvironment = NULL; OCIServer* g_pOciServer = NULL; OCISession* g_pOciSession = NULL; OCISvcCtx* g_pOciServiceContext = NULL; sb2* pIndicator=0; sb2* pIndicator2=0; sb2* pIndicator3=0; OCIDefine* pOciDefine; OCIDefine* pOciDefine2; OCIBind* pBind; OCIStmt* cursor; answer = OCIInitialize(OCI_THREADED, NULL, NULL, NULL, NULL); answer = OCIEnvInit(&g_pOciEnvironment, OCI_DEFAULT, 0, NULL); answer = OandleAlloc(g_pOciEnvironment, (void **)&pOciError, OCI_HTYPE_ERROR, 0, NULL); answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&g_pOciSession, OCI_HTYPE_SESSION, 0, NULL); answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&g_pOciServer, OCI_HTYPE_SERVER, 0, NULL); answer = OCIHandleAlloc(g_pOciEnvironment, (void **)&g_pOciServiceContext, OCI_HTYPE_SVCCTX, 0, NULL); answer = OCIServerAttach(g_pOciServer, pOciError, (unsigned char *)pConnectChar, strlen(pConnectChar), OCI_DEFAULT); answer = OCIAttrSet(g_pOciSession, OCI_HTYPE_SESSION, (unsigned char *)pUsernameChar, strlen(pUsernameChar), OCI_ATTR_USERNAME, pOciError); answer = OCIAttrSet(g_pOciSession, OCI_HTYPE_SESSION, (unsigned char *)pPasswordChar, strlen(pPasswordChar), OCI_ATTR_PASSWORD, pOciError); answer = OCIAttrSet(g_pOciServiceContext, OCI_HTYPE_SVCCTX, g_pOciServer, 0, OCI_ATTR_SERVER, pOciError); answer = OCIAttrSet(g_pOciServiceContext, OCI_HTYPE_SVCCTX, g_pOciSession, 0, OCI_ATTR_SESSION, pOciError); answer = OCISessionBegin(g_pOciServiceContext, pOciError, g_pOciSession, OCI_CRED_, OCI_DEFAULT); answer = OCIHandleAlloc(g_pOciEnvironment, (void **)(&pOciStatement), OCI_HTYPE_STMT, 0, NULL); answer = OCIStmtPrepare(pOciStatement, pOciError, (unsigned char *)sqlCharArray, strlen(sqlCharArray), OCI_NTV_SYNTAX, OCI_DEFAULT); answer = OCIHandleAlloc(g_pOciEnvironment, (void **)(&cursor), OCI_HTYPE_STMT, 0, NULL); answer = OCIBindByPos(pOciStatement,&pBind, pOciError, 1, &cursor, 0,SQLT_RSET, pIndicator2, 0,NULL, 0,0,OCI_DEFAULT); answer = OCIStmtExecute(g_pOciServiceContext, pOciStatement, pOciError, 1, 0, NULL, NULL, OCI_COMMIT_ON_SUCCESS); answer = OCIDefineByPos(cursor,&pOciDefine, pOciError,2,&id,sizeof(int), SQLT_INT,pIndicator, 0, 0,OCI_DEFAULT); answer = OCIDefineByPos(cursor,&pOciDefine2, pOciError,1,ename,40, SQLT_STR,pIndicator3, 0, 0,OCI_DEFAULT); if (answer == 0) while ((answer = OCIStmtFetch(cursor,pOciError, 1,OCI_FETCH_NEXT,OCI_DEFAULT)) == 0) { printf("fetched id %d and name %sn",id,ename); } answer = OCIHandleFree(pOciError, OCI_HTYPE_ERROR); return 0; }


And the following DBI perl example is thanks to q_richard_chen@yahoo.com (Richard Chen):

Hello Tom, I was looking for such compilation of on the topic. I did not find the section about doing it using the popular perl DBI. After some fiddling I get it working there too. Here is a complete working example following your model using perl DBI. I think it is a good idea that you include this in your howto so that more people will benefit from it. Thanks Richard Chen $ cat demo.pl #!/usr/local/bin/perl -w use strict; use DBI; use DBD::Oracle qw(:ora_types); my $dbh = DBI->connect('dbi:Oracle:','scott','tiger') or d$DBI::errstr; my $sth1 = $dbh->prepare(q{create or replace package types as type cursorType is ref cursor; end;}); $sth1->execute; > > $sth1 = $dbh->prepare(q{ 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;}); $sth1->execute; $sth1 = $dbh->prepare(q{ BEGIN :cursor := sp_ListEmp; END; }); my $sth2; $sth1->bind_param_inout(":cursor", $sth2, 0, { ora_type => ORA_RSET } ); $sth1->execute(); while ( my @row = $sth2->fetchrow_array ) { print join("|",@row),"n"; }




MFC + ODBC VERSION (example checked by Marcin Buchwald) marcin.buchwald@gazeta.pl Oracle server side code is just like in the 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 values of single row // use it here set.MoveNext(); } set.Close(); where COraSet::COraSet(CDatabase* pdb) : CRecordset(pdb) { m_nParams = 1; m_nFields = ; m_nDefaultType = snapshot; } CString COraSet::GetDefaultSQL() { return _T("{call RefTest.GetEmpData(?,?)}"); }


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/10748419/viewspace-976377/,如需轉載,請註明出處,否則將追究法律責任。

相關文章