如何从oracle存储过程返回动态游标

时间:2013-01-08 09:35:55

标签: oracle11g

我有2个表,其中ID字段很常见。

我正在获取游标中第一个表的所有记录。 然后我想做的是,根据光标中的每个ID,我想从第二个表中获取值然后返回。

我该怎么做...... 请帮忙!!!

1 个答案:

答案 0 :(得分:2)

功课?

这是基本的SQL。通常你会加入这两张桌子。

begin
  for r_row in (select b.*
                  from tab1 a 
                       inner join tab2 b
                               on b.id = a.id)
  loop
    null; -- do whatever
  end loop;
end;
/

如果您有现有光标但无法更改

例如,your_cursor只返回ID列。

begin
  open your_cursor;
  loop
    fetch your_cursor into v_id;
    exit when your_cursor%notfound;
    for r_row in (select * from tab2 b where b.id = v_id)
    loop
      null; -- do whatever here.
    end loop;
  end loop;
end;
/

编辑: 根据评论:

一些示例数据:

SQL> create table table1 (id number primary key, name varchar2(20));

Table created.

SQL> create table table2 (id number, col1 varchar2(20), col2 varchar2(20));

Table created.

SQL> insert into table1 values (1, 'test');

1 row created.

SQL> insert into table1 values (2, 'foo');

1 row created.

SQL>
SQL> insert into table2 values (1, 'John', 'Smith');

1 row created.

SQL> insert into table2 values (1, 'Peter', 'Jones');

1 row created.

SQL> insert into table2 values (1, 'Jane', 'Doe');

1 row created.

SQL> insert into table2 values (2, 'Nina', 'Austin');

1 row created.

SQL> insert into table2 values (2, 'Naman', 'Goyal');

1 row created.

SQL> commit;

Commit complete.

创建一个类型来保存返回结构。请注意数据类型NEED要匹配表table1table2的数据类型(%类型不起作用,因此请确保它们匹配)

SQL> create type my_obj as object (
  2    id number,
  3    name varchar2(20),
  4    col1 varchar2(20),
  5    col2 varchar2(20)
  6  );
  7  /

Type created.

SQL> create type my_tab as table of my_obj;
  2  /

Type created.

现在创建你的函数(你可以把它放在一个软件包中,如果在你的真实代码中你有这样的话)。

SQL> create function function1
  2    return my_tab pipelined
  3  is
  4  begin
  5    for r_row in (select t1.id, t1.name, t2.col1, t2.col2
  6                    from table1 t1
  7                         inner join table2 t2
  8                                 on t1.id = t2.id)
  9    loop
 10      pipe row(my_obj(r_row.id, r_row.name, r_row.col1, r_row.col2));
 11    end loop;
 12  end;
 13  /

Function created.

SQL>
SQL> select *
  2    from table(function1);

        ID NAME                 COL1                 COL2
---------- -------------------- -------------------- --------------------
         1 test                 John                 Smith
         1 test                 Peter                Jones
         1 test                 Jane                 Doe
         2 foo                  Nina                 Austin
         2 foo                  Naman                Goyal

如果需要,您可以将输入传递给该函数,例如table(function1('a', 'b'));等。

相关问题