---
title: "Oracle 返回 结果集"
author: "hwpok"
date: "2007-12-19T19:26:00Z"
tags: []
slug: "oracle"
draft: false
lastmod: "2007-12-19T19:26:00Z"
id: 615984
url: "https://hwpok.iteye.com/blog/615984"
---

过程返回记录集：  
CREATE OR REPLACE PACKAGE pkg\_test  
AS  
    TYPE myrctype IS REF CURSOR;  
    
    PROCEDURE get (p\_id NUMBER, p\_rc OUT myrctype);  
END pkg\_test;  
/  
    
CREATE OR REPLACE PACKAGE BODY pkg\_test  
AS  
    PROCEDURE get (p\_id NUMBER, p\_rc OUT myrctype)  
    IS  
       sqlstr   VARCHAR2 (500);  
    BEGIN  
       IF p\_id = 0 THEN  
          OPEN p\_rc FOR  
             SELECT ID, NAME, sex, address, postcode, birthday  
               FROM student;  
       ELSE  
          sqlstr :=  
             'select id,name,sex,address,postcode,birthday  
            from student where id=:w\_id';  
          OPEN p\_rc FOR sqlstr USING p\_id;  
       END IF;  
    END get;  
END pkg\_test;  
/  
    
函数返回记录集:  
建立带ref cursor定义的包和包体及函数：  
CREATE OR REPLACE  
package pkg\_test as  
/* 定义ref cursor类型  
    不加return类型，为弱类型，允许动态sql查询，  
    否则为强类型，无法使用动态sql查询;  
\*/  
   type myrctype is ref cursor;    
     
\--函数申明  
   function get(intID number) return myrctype;  
end pkg\_test;  
/  
     
CREATE OR REPLACE  
package body pkg\_test as  
\--函数体  
    function get(intID number) return myrctype is  
      rc myrctype;  --定义ref cursor变量  
      sqlstr varchar2(500);  
    begin  
      if intID=0 then  
         --静态测试，直接用select语句直接返回结果  
         open rc for select id,name,sex,address,postcode,birthday from student;  
      else  
         --动态sql赋值，用:w\_id来申明该变量从外部获得  
         sqlstr := 'select id,name,sex,address,postcode,birthday from student where id=:w\_id';  
         --动态测试，用sqlstr字符串返回结果，用using关键词传递参数  
         open rc for sqlstr using intid;  
      end if;  
     
      return rc;  
    end get;  
     
end pkg\_test;  
/