【问题标题】:How to sort an associative array in PL/SQL?如何在 PL/SQL 中对关联数组进行排序?
【发布时间】:2011-10-17 23:38:49
【问题描述】:

我有一个这样的关联数组:

continent_population('Australia') := 30;
continent_population('Antarctica') := 90;
continent_population('UK') := 50;

如何在 PL/SQL 中的值之后对该数组进行排序?谢谢!

【问题讨论】:

  • 排序后的关联数组是什么样的?键“澳大利亚”是否仍与数字 30 相关联?如果是这样,排序和未排序的关联数组有什么区别?
  • 我希望对这个数组进行排序,因为我需要按 ASC 顺序显示每个值,但仍然保持键和值之间的相关性。

标签: oracle collections plsql oracle10g


【解决方案1】:

您不能按值对关联数组进行排序,但您必须将数据转换为其他数据结构并在那里进行排序。最简单的方法是转换为另一个关联数组,其中键和值交换位置,但这要求您的键值也应该是唯一的。

以下是适用于您的案例的示例,来自Sorting PL/SQL Collections。有关详细信息,请查看该文章。

/* The sorting is done with SQL thus these types have to be SQL types. */

create type sortable_t is object(
  continent varchar2(32767),
  population number
);
/

create type sortable_table_t is table of sortable_t;
/

declare
  type continent_population_t is table of pls_integer index by varchar2(32767);
  continent_population continent_population_t;

  i varchar2(32767);

  sorted sortable_table_t := sortable_table_t();
begin
  /* Populate original data. */

  continent_population('Australia') := 30;
  continent_population('Antarctica') := 90;
  continent_population('UK') := 50;
  continent_population('USA') := 50;

  /* Convert to a helper data type that is used for sorting. */

  i := continent_population.first;

  while i is not null loop
    sorted.extend(1);
    sorted(sorted.last) := new sortable_t(i, continent_population(i));
    i := continent_population.next(i);
  end loop;

  /* Show that the content is not sorted yet. */

  dbms_output.put_line('Unsorted:');
  for j in sorted.first .. sorted.last loop
    dbms_output.put_line(sorted(j).continent || ' = ' || sorted(j).population);
  end loop;

  /* Sorting with SQL. */

  select cast(multiset(select *
                       from table(sorted)
                       order by 2 asc, 1 asc)
              as sortable_table_t)
    into sorted
    from dual;

  /* Show that the content is now sorted. */

  dbms_output.put_line('Sorted by value:');
  for j in sorted.first .. sorted.last loop
    dbms_output.put_line(sorted(j).continent || ' = ' || sorted(j).population);
  end loop;

end;
/

打印:

Unsorted:
Antarctica = 90
Australia = 30
UK = 50
USA = 50
Sorted by value:
Australia = 30
UK = 50
USA = 50
Antarctica = 90

【讨论】:

    【解决方案2】:

    接受的答案已过时。从 Oracle 12c 开始,只要在包规范中声明类型,就可以使用 TABLE 运算符查询关联数组:https://galobalda.wordpress.com/2014/08/02/new-in-oracle-12c-querying-an-associative-array-in-plsql-programs/

    可以按值对关联数组进行排序,而您不必转换数据: Sorting an index-by table (associative array)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-27
      • 2016-02-01
      • 1970-01-01
      • 2011-07-26
      • 2011-05-01
      • 1970-01-01
      相关资源
      最近更新 更多