oracle configurable FETCH FIRST n ROWS ONLY(检索1、n或所有行)?

6jjcrrmo  于 2023-03-22  发布在  Oracle
关注(0)|答案(2)|浏览(133)

当使用FETCH FIRST n ROWS ONLY子句时,有没有办法让select语句检索ALL行?
假设我有这个函数:

function fill_ids_array(n in number default 1) is
begin
  select id
    into t_ids_array
    from some_table
   fetch first n rows only;
end;

如何让这个函数将所有id填充到数组变量中?

rqqzpn5f

rqqzpn5f1#

就像那样。

SQL> create or replace function fill_ids_array(n in number default 1)
  2    return number
  3  is
  4    l_tab sys.odcinumberlist;
  5  begin
  6    select empno
  7      bulk collect into l_tab
  8      from emp
  9      fetch first n rows only;
 10
 11    return l_tab.count;
 12  end;
 13  /

Function created.

测试:

SQL> select fill_ids_array(6) cnt from dual;

       CNT
----------
         6

SQL> select fill_ids_array(3) cnt from dual;

       CNT
----------
         3

SQL> select fill_ids_array cnt from dual;

       CNT
----------
         1

SQL>
hvvq6cgz

hvvq6cgz2#

当需要所有行时,可以使用IF语句来处理这种情况:

FUNCTION fill_ids_array(
  n in number default 1
) RETURN number_list
IS
  t_ids_array number_list;
BEGIN
  IF n IS NULL THEN
    -- All rows
    SELECT id
    BULK COLLECT INTO t_ids_array
    FROM   some_table;
  ELSE
    -- Specified number of rows
    SELECT id
    BULK COLLECT INTO t_ids_array
    FROM   some_table
    FETCH FIRST n ROWS ONLY;
  END IF;

  RETURN t_ids_array;
END;

如果你想明确地表示你想要所有的行,那么你可以用途:

FETCH FIRST 100 PERCENT ROWS ONLY

相关问题