暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 将集合 (或等效集合) 连接到表。

askTom 2017-02-21
446

问题描述

我需要构建一个过程,该过程将接受我需要在表中找到匹配项的数字集合。如果集合的元素在另一个表中,那么连接这些表将是一个简单的情况。我如何用收藏来完成这个?

create or replace type numberList 
    is table of number;
/

create table COLLECTION_TEST (
    I number, 
    J number, 
    A varchar2(100) 
    );
/

insert into COLLECTION_TEST 
    (I, J, A) 
select 1, 1, 'Type One1' from dual
union
select 1, 2, 'Type One2' from dual
union
select 2, 1, 'Type Two1' from dual
union
select 2, 2, 'Type Two2' from dual
union
select 3, 1, 'Type Three1' from dual
union
select 3, 3, 'Type Three3' from dual
;
commit; 
/

declare 
    COLLECTION_TEST2 numberList;
begin 
    COLLECTION_TEST2 := numberList(); 
    
    COLLECTION_TEST2.extend;
    COLLECTION_TEST2(1) := 1;
    COLLECTION_TEST2.extend;
    COLLECTION_TEST2(2) := 2; 
    
/*
    select ct.A 
        collect or bulk collect into a collection 
    from COLLECTION_TEST ct 
    join COLLECTION_TEST2 ct2 
        on ct2 = ct.j;
*/
end;
/

drop table COLLECTION_TEST;
/


请注意,numberList可以有1到N个元素,注释中的join只是为了说明。

提前感谢,


专家解答

真棒测试用例... 让我们的生活变得轻松多了!

你已经非常接近答案了。TABLE子句允许您 “关系化” 嵌套表集合

SQL> create or replace type numberList
  2      is table of number;
  3  /

Type created.

SQL>
SQL> create table COLLECTION_TEST (
  2      I number,
  3      J number,
  4      A varchar2(100)
  5      );

Table created.

SQL>
SQL> insert into COLLECTION_TEST
  2      (I, J, A)
  3  select 1, 1, 'Type One1' from dual
  4  union
  5  select 1, 2, 'Type One2' from dual
  6  union
  7  select 2, 1, 'Type Two1' from dual
  8  union
  9  select 2, 2, 'Type Two2' from dual
 10  union
 11  select 3, 1, 'Type Three1' from dual
 12  union
 13  select 3, 3, 'Type Three3' from dual
 14  ;

6 rows created.

SQL> commit;

Commit complete.

SQL> /

Commit complete.

SQL>
SQL> set serverout on
SQL> declare
  2      n numberList;
  3  begin
  4      n := numberList();
  5
  6      n.extend;
  7      n(1) := 1;
  8      n.extend;
  9      n(2) := 2;
 10
 11      for i in (
 12      select ct.A
 13      from COLLECTION_TEST ct
 14      join table(n) ct2
 15          on ct2.column_value = ct.j
 16      )
 17      loop
 18        dbms_output.put_line(i.a);
 19      end loop;
 20
 21  end;
 22  /
Type One1
Type One2
Type Two1
Type Two2
Type Three1

PL/SQL procedure successfully completed.



「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论