2

我可以轻松地创建返回 myTable%ROWTYPE 的函数,但是如果我的查询(在函数中)作为另一个表中的另一列怎么办?

t1_rec t1%ROWTYPE;

我是否将新字段附加到主表或什么?

SELECT t1.col1, t1.col2, t1.col3, t2.col4...

问题

如何有效地创建记录类型以包含上述查询的结果集?

我想要的是类似的东西

t1_rec t1%ROWTYPE (plus another column for t2.col4%TYPE inside t1_rec)

抱歉,起初的问题含糊不清。

4

1 回答 1

2

您可以使用强类型游标及其行类型:

-- example data
create table t1(pk number not null primary key, val varchar2(30));
create table t2(
  pk number not null primary key, 
  t1_fk references t1(pk), 
  val varchar2(30));

insert into t1(pk, val) values(1, 'value1');
insert into t2(pk, t1_fk, val) values(1, 1, 'value2a');
insert into t2(pk, t1_fk, val) values(2, 1, 'value2b');

declare
  cursor cur is 
  select t1.*, t2.val as t2_val 
  from t1
  join t2 on t1.pk = t2.t1_fk;

  function get_data(arg in pls_integer) return cur%rowtype is
      l_result cur%rowtype;
    begin
      select t1.*, t2.val as t2_val 
        into l_result 
        from t1 
        join t2 on t1.pk = t2.t1_fk
        where t2.pk = arg;
      return l_result;
    end;
begin
  dbms_output.put_line(get_data(2).t2_val);
end;

更新:您可以轻松地将游标和函数包装在 PL/SQL 包中:

create or replace package pkg_get_data as 

  cursor cur is 
  select t1.*, t2.val as t2_val 
  from t1
  join t2 on t1.pk = t2.t1_fk;

  function get_data(arg in pls_integer) return cur%rowtype;
end;

(包体省略)

于 2013-07-16T07:56:13.220 回答