메뉴 건너뛰기

tnt_db

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 up of the database you have cursor variables.  Cursor variables are cursors opened by a pl/sql 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 decide 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, 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', %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.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();
  }
}
번호 제목 글쓴이 날짜 조회 수
86 LENGTH/LENGTHB,SUBSTR/SUBSTRB,INSTR/INSTRB 운영자 2002.09.18 4050
85 PARAMETER값 변경에따른 유연한 GROUP BY 운영자 2002.09.18 4040
84 최대값과 최소값을 뺀 평균 운영자 2002.09.18 3941
83 한번 읽은 테이블로 백분율 구하기 운영자 2002.09.18 3834
82 plan table(sql실행계획) 보는 select문 운영자 2003.01.28 3831
81 다중 Row 결과를 단일행으로 컴마로 분리해 출력하는 방법 (2) 박상현 2006.06.13 3816
80 sybase DB에서 파일로 백업을 받구 그파일을 다시 DB2로 임포트하는방법 원우석 2004.07.31 3748
79 특정문자까지의 왼쪽 문자열 반환 function 운영자 2002.10.18 3743
78 row데이터 연결하여 조회 구퍼 2009.03.31 3663
77 년중 몇번째 주간인지 알아내기(FUNCTION) - ORACLE이 제공하는 것과 다름 운영자 2002.09.17 3630
76 최단거리찾기 혹은 멀리 떨어진 두지점간의 거리의 합구하기 박상현 2006.11.07 3608
75 다수 NULL 허용 COLUMN의 명칭을 가져올때 운영자 2002.09.18 3572
74 문자열 행으로 분리하기 박상현 2006.06.13 3552
73 다중 Row 결과를 단일행으로 컴마로 분리해 출력하는 방법 (1) 박상현 2006.06.13 3537
72 복제를이용한 합계계에서 비율계산 운영자 2002.09.18 3534
71 RECORD단위 DATA를 COLUMN단위로 운영자 2002.09.18 3507
70 sql 문 실행명령 원우석 2004.07.31 3500
69 최대공약수, 최소공배수 구하기 박상현 2006.06.13 3479
68 PL/SQL에서 쿼리시 Array Processing 처리방법 박상현 2006.10.27 3469
67 반올림 DATA의 오차보정 운영자 2002.09.18 3463
위로