4

SQL Server 能够在一次往返中返回多个查询的结果,例如:

select a, b, c from y;
select d, e, f from z;

Oracle 不喜欢这种语法。可以使用参考游标,如下所示:

begin 
  open :1 for select count(*) from a; 
  open :2 for select count(*) from b; 
end; 

但是,您在打开/关闭游标时会受到惩罚,并且您可以长时间持有数据库锁。我想做的是使用 Odp.net 一次性检索这两个查询的结果。可能吗?

4

1 回答 1

6

在 Oracle 中,引用游标是指向数据的指针,而不是数据本身。因此,如果一个过程返回两个引用游标,客户端仍然必须从这些游标中获取行(并导致网络命中)。

因此,如果数据量很小,您可能希望调用一个只返回值的过程。如果数据量很大(数千行),那么无论如何它都不会是一次网络旅行,因此在游标之间切换时额外的一两次不会有太大的区别。

另一种选择是让单个选择返回所有行。这可能是一个简单的 UNION ALL

select a, b, c from y union all select d, e, f from z;

它可能是一个流水线表函数

create or replace package test_pkg is
    type rec_two_cols is record
        (col_a  varchar2(100),
        col_b       varchar2(100));
    type tab_two_cols is table of rec_two_cols;
    function ret_two_cols return tab_two_cols pipelined;
end;
/

create or replace package body test_pkg is
    function ret_two_cols return tab_two_cols pipelined
    is
        cursor c_1 is select 'type 1' col_a, object_name col_b from user_objects;
        cursor c_2 is select 'type 2' col_a, object_name col_b from user_objects;
        r_two_cols  rec_two_cols;
    begin
        for c_rec in c_1 loop
            r_two_cols.col_a := c_rec.col_a;
            r_two_cols.col_b := c_rec.col_b;
            pipe row (r_two_cols);
        end loop;
        for c_rec in c_2 loop
            r_two_cols.col_a := c_rec.col_a;
            r_two_cols.col_b := c_rec.col_b;
            pipe row (r_two_cols);
        end loop;
        return;
    end;
end;
/
select * from table(test_pkg.ret_two_cols);

我相信 11g 的最新版本的 ODP 允许用户定义类型,这可能会有所帮助。

于 2010-03-24T23:22:33.377 回答