一个父sys_refcursor记录包含具有多个记录的子sys_refcursor类型

时间:2015-02-10 06:45:24

标签: sql plsql oracle11g

DB:Oracle 11gR2

您好,

我有2个表,它们之间有父子关系(一对多)。现在我需要从存储过程返回一个ref-cursor,它将从父表中返回一行,对应于输入参数,并从子表中返回相应的记录(可以是一个数组)。请注意,我们不希望从父级重复结果集。所以基本上我们只想返回一条记录,其中detail列是一个记录数组或父sys recursor中的子sys refcursor。问题是我该怎么做?

下面是示例表,数据和通常的过程(返回多行 - 这不是意图):

create table parent 
(
    class_id        varchar2(2),
    class_name      varchar2(10),
    subject_name    varchar2(10),
    constraint pk_id primary key (class_id)
);

create table child
(
    class_id      varchar2(10),
    student_name    varchar2(10),
    result          varchar2(10),
    constraint fk_id Foreign key (class_id) references parent(class_id)
);

insert into parent values('1', 'class_1', 'subject_1');
insert into parent values('2', 'class_2', 'subject_2');
insert into parent values('3', 'class_3', 'subject_3');
insert into parent values('4', 'class_4', 'subject_4');

insert into child values ('1', 'student_1', 'pass');
insert into child values ('1', 'student_2', 'fail');
insert into child values ('1', 'student_3', 'pass');
insert into child values ('2', 'student_1', 'pass');
insert into child values ('2', 'student_4', 'fail');

create or replace PROCEDURE get_data (
    class_id_in        IN      parent.class_id%TYPE,
    student_list_cur   OUT     SYS_REFCURSOR)
AS
BEGIN
    OPEN student_list_cur FOR
    SELECT p.class_name,
           p.subject_name,
           c.student_name,
           c.result
    FROM parent p, child c
    WHERE p.class_id = c.class_id
    AND p.class_id = class_id_in;

END get_data;

再次注意sys-refcursor返回:

class_name     subject_name     student_name     result
-------------------------------------------------------
class_1         subject_1       student_1        pass
class_1         subject_1       student_2        fail
class_1         subject_1       student_3        pass

而我想要的是一条记录,如:

parent.class_name,
parent.subject_name,
child.array_of_records SYS_REFCURSOR

其中child.array_of_records包含child.student_name,child.result的多个记录,对应于同一个class_id。

感谢。

1 个答案:

答案 0 :(得分:0)

您正在寻找CURSOR SUBQUERY

OPEN student_list_cur FOR
SELECT p.class_name,
       p.subject_name,
       CURSOR(SELECT c.student_name,
                     c.result
              FROM
                 child c
              WHERE p.class_id = c.class_id)
FROM parent p
WHERE p.class_id = class_id_in;