Tro*_*ame 3 arrays sorting oracle plsql oracle11g
这是Oracle 11.2g.在PL/SQL函数中,我有一个循环,每次迭代,我创建一个字符串和一个与该字符串相关的整数.该函数返回所有生成的字符串的最终串联,按字母顺序或整数值排序(取决于函数输入参数).提出一个想法,我生成这样的东西:
Iteration String Integer
1 Oslo 40
2 Berlin 74
3 Rome 25
4 Paris 10
Run Code Online (Sandbox Code Playgroud)
如果输入参数按字母顺序排序,则函数输出应如下所示:
Berlin, Oslo, Paris, Rome
Run Code Online (Sandbox Code Playgroud)
否则,我们返回按相关整数的值排序的连接字符串:
Paris, Rome, Oslo, Berlin
Run Code Online (Sandbox Code Playgroud)
实现这种最合适的数据结构是什么?我看过集合,关联数组甚至varrays.我有点震惊的是,在Oracle中实现这一目标有多么困难.我看到了这个问题,但它在我的情况下不起作用,因为我需要能够按索引和值排序:如何在PL/SQL中对关联数组进行排序?这种情况是否有更合适的数据结构,您将如何对其进行排序?
谢谢!
如果将PL/SQL用作SQL而非其他语言,则非常容易.这是非常具体的,有时非常好,正是因为如此.
有时我真的很讨厌PL/SQL,但这种情况绝对是爱情.
看看它有多容易:
create type it as object (
iter number,
stringval varchar2(100),
intval integer
);
create type t_it as table of it;
declare
t t_it := new t_it();
tmp1 varchar2(32767);
tmp2 varchar2(32767);
begin
t.extend(4);
t(1) := new it(1,'Oslo',40);
t(2) := new it(2,'Berlin',74);
t(3) := new it(3,'Rome',25);
t(4) := new it(4,'Paris',10);
select listagg(stringval,', ') within group (order by stringval),
listagg(stringval,', ') within group (order by intval)
into tmp1, tmp2
from table(t);
dbms_output.put_line(tmp1);
dbms_output.put_line(tmp2);
end;
/
drop type t_it;
drop type it;
Run Code Online (Sandbox Code Playgroud)
在这里你可以看到你必须创建全局类型的问题,这就是我讨厌它的问题.但是他们在Oracle 12中说可以用本地定义的类型来完成,所以我在等它:)
输出是:
Berlin, Oslo, Paris, Rome
Paris, Rome, Oslo, Berlin
Run Code Online (Sandbox Code Playgroud)
编辑
至于你从一开始就不知道迭代的数量,唯一的方法是在每次迭代时进行扩展(这只是扩展的例子):
declare
iterator pls_integer := 1;
begin
/* some type of loop*/ loop
t.extend();
-- one way to assign
t(t.last) := new it(1,'Oslo',40);
-- another way is to use some integer iterator
t(iterator) := new it(1,'Oslo',40);
iterator := iterator + 1;
end loop;
end;
Run Code Online (Sandbox Code Playgroud)
我更喜欢第二种方式,因为它更快(不会.last在每次迭代时计算).