如何在PL / SQL中对数字表进行排序?

时间:2019-06-11 12:15:29

标签: oracle plsql collections

我想通过使用plsql中的集合以升序显示数字。

我有如下代码。它将以未排序的顺序显示数字,但我想以已排序的顺序显示

DECLARE
    TYPE num_asc IS
        TABLE OF NUMBER;
    rec_num   num_asc;
    v_var     NUMBER;
BEGIN
    rec_num := num_asc(10,21,13,14,52,16);
    FOR i IN rec_num.first..rec_num.last LOOP
        dbms_output.put_line (rec_num (i));
    END LOOP;
END;
Required result:  
10  
13  
14  
16  
21  
52

4 个答案:

答案 0 :(得分:4)

使用SQL。这肯定是最少的代码,而且可能是最有效的方法。只需将集合类型更改为我们可以在table()函数中使用的类型:

DECLARE
    rec_num  sys.odcinumberlist;
BEGIN
    rec_num := sys.odcinumberlist(10,21,13,14,52,16);
    for i in (select * from table(rec_num) order by 1)
    loop
        dbms_output.put_line(i.column_value);
    end loop;
END;

答案 1 :(得分:3)

要对集合进行排序,您需要在架构级别定义类型。

CREATE TYPE num_asc IS TABLE OF NUMBER;

您可以在带有ORDER BY子句的select语句中使用它。

DECLARE
    rec_num   num_asc;
    v_var     NUMBER;
BEGIN
    rec_num := num_asc(10, 21, 13, 14, 52, 16);

    --Sorting rec_num
    SELECT CAST (MULTISET (
        SELECT *
          FROM TABLE (rec_num)
         ORDER BY 1
    ) AS num_asc)
      INTO rec_num
      FROM dual;
    FOR i IN rec_num.first..rec_num.last LOOP
        dbms_output.put_line (rec_num (i));
    END LOOP;
END;

信用归卢卡斯·耶勒玛(Lucas Jellema)负责,他发表了有关该主题的几篇文章。

答案 2 :(得分:2)

可以对列表进行排序而无需收集-确保其中有很多。无论如何,您都可以对其进行编程。例如,以CSV字符串开头的纯SQL解决方案:

with num_list as (select '10, 21, 13, 14, 52, 16' val from dual )
select v
  from 
      ( select trim(regexp_substr(val,'[^,]+', 1, level)) v 
          from num_list
          connect by trim(regexp_substr(val,'[^,]+', 1, level)) is not null
       )
order by v;

答案 3 :(得分:1)

由于您使用的是PL / SQL集合,因此只需编写一些小程序即可对它们进行排序:

DECLARE
  TYPE num_asc IS TABLE OF NUMBER; 

  rec_num  num_asc;
  v_var    number;

  PROCEDURE sort_numbers(pioNumbers IN OUT num_asc) IS
    bSwapped  BOOLEAN := FALSE;
    bRepeat   BOOLEAN := TRUE;
    nTemp     NUMBER;
  BEGIN
    WHILE bRepeat LOOP
      FOR i IN 1..pioNumbers.COUNT-1 LOOP
        IF pioNumbers(i+1) < pioNumbers(i) THEN
          nTemp := pioNumbers(i);
          pioNumbers(i) := pioNumbers(i+1);
          pioNumbers(i+1) := nTemp;
          bSwapped := TRUE;
        END IF;
      END LOOP;  -- i

      bRepeat := bSwapped;
      bSwapped := FALSE;
    END LOOP;  -- bRepeat
  END sort_numbers;

  PROCEDURE print_numbers(pinMsg     IN VARCHAR2,
                          pinNumbers IN num_asc) IS
  BEGIN
    DBMS_OUTPUT.PUT_LINE(pinMsg);

    for i in pinNumbers.first .. pinNumbers.last loop
      dbms_output.put_line(pinNumbers(i));
    end loop;
  END print_numbers;
BEGIN
  rec_num := num_asc(10,21,13,14,52,16);

  print_numbers('Before sort', rec_num);

  sort_numbers(rec_num);

  print_numbers('After sort', rec_num);
END;

产生以下输出:

Before sort
10
21
13
14
52
16
After sort
10
13
14
16
21
52

好运。