【问题标题】:Oracle PL/SQL query nested table collection and value key nameOracle PL/SQL 查询嵌套表集合和值键名
【发布时间】:2013-09-19 23:15:26
【问题描述】:

我正在寻找一个嵌套表,以便我可以使用查询来重新排序值。由于没有键名,我想知道列名是什么?

我知道这不是正确的语法,但它说明了我想要实现的目标。

CREATE OR REPLACE TYPE a_nested_table AS TABLE OF VARCHAR2(20);

CREATE OR REPLACE FUNCTION my_func RETURN VARCHAR2 IS
    output VARCHAR2;
    list a_nested_table := a_nested_table('foo', 'bar');
BEGIN
    FOR current_record IN( 
        SELECT column_name INTO bar
        FROM TABLE(CAST(list AS a_nested_table))
        ORDER BY UPPER(column_name) ASC
    ) LOOP
        output := output || current_record.column_name
    END LOOP;

    return output;
END my_func;

【问题讨论】:

  • 带有column_value 的 order by 子句应该可以解决问题,你试过了吗?
  • 你总是可以使用位置符号,例如ORDER BY 1. 如果对我在博客中对嵌套表进行排序有帮助:oraclefrontovik.com/2013/08/sorting-an-oracle-nested-table
  • @Sebas 是的,column_value 有效。 @IanCarpenter 我用过FOR current_record IN(/* select statement */) LOOP;性能方面,这与您的 SELECT CAST(MULTISET(/* select statement*/)) INTO nested_table FROM DUAL 方法有何不同?

标签: oracle collections plsql oracle10g


【解决方案1】:

如果您是 11.2 或更高版本,则可以使用 LISTAGG 函数:

create or replace type a_nested_table as table of varchar2(20);

create or replace function my_func return varchar2 is
  result varchar2(4000);
  list   a_nested_table := a_nested_table('aa', 'bb', 'cc', 'dd', 'ee');
begin
  select listagg(column_value, ' ') within group(order by column_value desc)
    into result
    from table(list);

  return(result);
end my_func;

...

SQL> select my_func from dual;
MY_FUNC
--------------------------------------------------------------------------------
ee dd cc bb aa

有关使用 LISTAGG 功能的更多信息,请参阅documentation

更新:

对于 10g 版本:

create or replace type a_nested_table is table of varchar(20);

create or replace function my_func return varchar2 is
  list    a_nested_table := a_nested_table('aa', 'bb', 'cc', 'dd', 'ee');
  result varchar2(4000);
begin
  for c1 in (select column_value col_val from table(list) order by 1 desc) loop
    result := result || ' ' || c1.col_val;
  end loop;
  return result;
end my_func;

SQL> select my_func from dual;
MY_FUNC
--------------------------------------------------------------------------------
ee dd cc bb aa

【讨论】:

  • 我不是10。发现使用tables有上限,会报错
猜你喜欢
  • 1970-01-01
  • 2012-10-26
  • 2017-07-17
  • 2013-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-24
相关资源
最近更新 更多