如何将JOIN结果表示为普通行?收藏,游标?

时间:2016-06-22 11:03:08

标签: oracle plsql

我有一个简单的例子(下面是SQL)我的意思(例如,在PL / SQL Developer中,它很容易可视化)。 所以我们有主实体表和相关的主要实体细节,1..N关系是可能的。 我们有一个java应用程序,它应该请求与存储过程类似结构的数据的连接结果。 在java方面,使用了Hibernate技术。

当然我可以返回一个带有JOIN操作结果的游标。但我们必然会处理重复, 想象一下,如果有许多主要实体细节表,它们会有多少。

WITH main_table as (
  select 1 as id , 'property 1' as property from dual
  union all 
  select 2 as id , 'property 2' as property from dual
), 
details_table as(
  select 1 as main_table_id , 'value 1' as val from dual
  union all
  select 2 as main_table_id , 'value 12' as val from dual
  union all
  select 2 as main_table_id , 'value 13' as val from dual
)
select mt.id
     , mt.property
     , cursor (select main_table_id, val from details_table where main_table_id = mt.id)
  from main_table mt

是否可以传递结果(如我的例子中所示),如

1. <id>, <main_property>, <cursor_with_details1>, <cursor_with_details2>

或者

2. <id>, <main_property>, <collection_with_details1>, <collection_with_details2> 

或者别的什么?最佳做法是什么?我相信有一种方法能够以最接近java对象的方式表示结果,这些对象可能具有相当复杂的层次结构。

我已将第一种方法实施为:

create or replace function fn_complicated_cursor return sys_refcursor
  is
  v_ret_cur sys_refcursor;
begin
    open  v_ret_cur 
     for  WITH main_table as (
            select 1 as id , 'property 1' as property from dual
            union all 
            select 2 as id , 'property 2' as property from dual
          ), 
          details_table as(
            select 1 as main_table_id , 'value 1' as val from dual
            union all
            select 2 as main_table_id , 'value 12' as val from dual
            union all
            select 2 as main_table_id , 'value 13' as val from dual
          )
          select mt.id
               , mt.property
               , cursor (select main_table_id, val 
                           from details_table 
                          where main_table_id = mt.id)
            from main_table mt;
    return v_ret_cur;    
end fn_complicated_cursor;

0 个答案:

没有答案