oracle - 如何在 PL/SQL 中对关联数组进行排序?

标签 oracle collections plsql oracle10g

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

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

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

最佳答案

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

以下是适用于您的案例的示例,来自 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

关于oracle - 如何在 PL/SQL 中对关联数组进行排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7800880/

相关文章:

oracle - 如何在 Oracle apex 中提供多个构建选项

java - 随机错误 - java.lang.IllegalArgumentException : Comparison method violates its general contract

sql - PLSQL - 在批量收集的嵌套表中搜索记录

oracle - 在 PL/SQL 中获取相似的字符串并具有良好的性能

database - 在 PL/SQL 中使用 "select *"作为游标是否被认为是糟糕的编程?

java - 将数据库字段值加载到 JCombobox

java - processBuilder 无法在不同主机上加载数据?

java - Jsoup:对元素进行排序

java - 同步集合/列表的映射

oracle - USER() 和 SYS_CONTEXT ('USERENV' ,'CURRENT_USER' 有什么区别?