Oracle Procedure return a Result Set

       In this article, I will introduce how to use oracle procedure to get a cursor type result set. I will represent by illustration.

1.Create an example table and add some data:

 

View Code
 1  CREATE   TABLE  USER_INFO
 2  (
 3      User_ID   integer   primary   key , -- Primary key
 4      User_Name   varchar2 ( 20 ),
 5     sex  varchar2 ( 2 )
 6  );
 7 
 8  insert   into  user_info( user_name ,sex)  values ( ' David.Tian ' , ' M ' );
 9 
10  insert   into  user_info( user_name ,sex)  values ( ' Lucy ' , ' F ' );
11 
12  commit ;
13 
14  select   *   from  user_info;

 

2. Create a procedure with at least one out parameter, the parameter type is sys_refcursor.

 

View Code
create   or   replace   procedure  getResult(p_cursor out sys_refcursor)
as
begin
  
open  p_cursor  for
  
select   *   from  user_info;
end ;

 

3. The following code illustrates how to use the result set of sys_refcursor.

 

View Code
declare
  v_cursor sys_refcursor;
  u user_info
% rowtype;
begin
  getResult(v_cursor);
  loop 
  
fetch  v_cursor  into  u. user_id , u. user_name ,u.sex;          
  
exit   when  v_cursor % notfound;
  dbms_output.put_line(u.
user_id || ' - ' || u. user_name || ' - ' || u.sex);
  
end  loop;
end ;

Conclusion: You can use the result set not only in the anonymous block, you can also use it in a function, a procedure, a trigger.

                 Any questions, please send me email: [email protected]

 

你可能感兴趣的:(procedure)