Plsql 从用户输入读取“n”元素数组

Plsql 从用户输入读取“n”元素数组,plsql,Plsql,如何动态读取n个元素的数组并在plsql中显示元素 下面是我的代码,我是plsql编程新手 set serveroutput on set verify on declare type myarray is table of number index by binary_integer; x myarray; i pls_integer; n number; begin -- populate array dbms_output.put_line('Ente

如何动态读取n个元素的数组并在plsql中显示元素

下面是我的代码,我是plsql编程新手

set serveroutput on
set verify on
declare
   type myarray is table of number index by binary_integer;
   x myarray;
   i pls_integer;
   n number;

begin
   -- populate array
   dbms_output.put_line('Enter number of array elements');
   n := &n;
   dbms_output.put_line('Enter elements one by one');
   for i in 1..n loop
  dbms_output.get_lines(&&x(i),n);
   end loop;
   i :=0;

   -- print array
   loop
           i := i + 1;
           begin
                   dbms_output.put_line(x(i));
           exception
                   when no_data_found then exit;
           end;
   end loop;

   end;
   /
  quit;

我偶然遇到了同样的问题,想尝试一下

您可以使用一种残酷的方法来实现这一点,即在您希望向数组添加值的任何时候使用shell来调用客户机,即sqlplus。我编写了一个小程序包,将数组的值存储在一个表中。然后您可以更改存储值的方式,但原则将保持不变:

 -- this package uses "execute immediate" statements for everything
 -- because it assumes the temporary table T_MY_ARRAY can be non-existent.
 create or replace package my_array
  authid current_user
is
  TYPE a_TBL_Number IS TABLE OF Number INDEX BY BINARY_INTEGER; 
  procedure init;
  procedure add(v in number);
  procedure display;
  function to_var return a_TBL_Number;
end my_array;
/
create or replace package body my_array
is     
  procedure init is
  -- create table if needed, then make sure its empty;
  begin
    begin
      execute immediate 'create table T_MY_ARRAY(c1 number)';
    exception when others then
      -- dbms_output.put_line(sqlerrm);
      -- we're never sure the temp. table already exists. So create it and catch if existing.
      null;
    end;
    execute immediate 'truncate table T_MY_ARRAY';
  end init;

  procedure add(v in number) is
  -- add new value
  begin
    execute immediate 'insert into T_MY_ARRAY (c1) values ('||v||')';
  end add;

  function to_var return a_TBL_Number is
  -- hand out an array with the values
    t_TBL_n a_TBL_Number; 
  begin
    execute immediate 'select c1 from T_MY_ARRAY ' bulk collect into t_TBL_n;
    return t_TBL_n;
  end to_var;

  procedure display is
    t_TBL_n a_TBL_Number; 
  begin
    t_TBL_n:=my_array.to_var();
    for i in 1..t_TBL_n.count loop
      dbms_output.put_line(t_TBL_n(i));
    end loop;
  end display;

end my_array;
/
然后,这里是如何从一个shell中调用它的,这是一个旧ksh:

读取SQL\u CONNECT?输入您的SQL连接字符串: 读取n?输入数组元素数: 首先初始化数组:
sqlplus-s${SQL\U CONNECT}dbms\U output.get\U行不从输入读取数据。它从dbms_输出缓冲区读取行。你把sql*plus命令和pl/sql混淆了。请用一个音节的单词来帮助我如何做到这一点——你不能。PL/SQL未设置为接受交互式用户输入。我建议您将数组元素放在一个文件中,逐行读取文件。请参阅UTL_文件包,使用TO_NUMBER将从文件中读取的字符串转换为数字,并将这些数字存储到数组中。但我不熟悉使用PL/SQL从终端读取输入的方法。祝你好运。@Bob Jarvis。您好,先生,谢谢您的回复。请帮助我如何在我的情况下使用utl文件。hoe将文件数据作为数组元素传递。另一种解决方案的可能重复是使用递归调用sql脚本进行处理,如此处所建议的:;但是,您仍然不能仅使用plsql来实现这一点,并且需要在这里使用客户端sqlplus。