在 plsql 存储过程中使用 varrays 时遇到错误无法从非嵌套 table 项访问行
Facing error Cannot access rows from a non-nested table item when using varrays in plsql stored procedure
我是 plsql 的初学者,我正在尝试编写一个程序来计算 table 中存在的记录数,并将结果放入另一个 table 中。现在有多个 tables 我想这样做,所以我把它们放在一个 varray 中,但我面临上述错误
Create Or Replace Procedure count
AS
type arr IS VARRAY(5) OF VARCHAR2(30);
tables arr :=arr('tb1','tb2','tb3','tb4','tb5');
cnt NUMBER;
BEGIN
FOR i in 1 .. tables.COUNT
LOOP
select Count(*) INTO cnt from tables(i);
insert into tb6 VALUES(tables(i),cnt);
END LOOP
END;
为此你需要 动态 SQL。
方法如下:一些示例 table(基于 Scott 的 emp
table),以及包含结果的 tb6
:
SQL> create table tb6 (val varchar2(10), cnt number);
Table created.
SQL> create table tb1 as select * from emp where deptno = 10;
Table created.
SQL> create table tb2 as select * from emp where deptno = 20;
Table created.
SQL> create table tb3 as select * from emp where deptno = 30;
Table created.
我期望哪个结果?
SQL> select deptno, count(*) from emp group by deptno order by deptno;
DEPTNO COUNT(*)
---------- ----------
10 3
20 5
30 6
程序:
SQL> create or replace procedure p_count as
2 type arr is varray(5) of varchar2(30);
3 tables arr := arr('tb1', 'tb2', 'tb3');
4 cnt number;
5 begin
6 for i in 1 .. tables.count loop
7 execute immediate 'select count(*) from ' || tables(i) into cnt;
8 insert into tb6 values(tables(i), cnt);
9 end loop;
10 end;
11 /
Procedure created.
测试:
SQL> set serveroutput on
SQL> exec p_count;
PL/SQL procedure successfully completed.
SQL> select * from tb6;
VAL CNT
---------- ----------
tb1 3
tb2 5
tb3 6
SQL>
如您所见,tb6
内容符合预期值。
我是 plsql 的初学者,我正在尝试编写一个程序来计算 table 中存在的记录数,并将结果放入另一个 table 中。现在有多个 tables 我想这样做,所以我把它们放在一个 varray 中,但我面临上述错误
Create Or Replace Procedure count
AS
type arr IS VARRAY(5) OF VARCHAR2(30);
tables arr :=arr('tb1','tb2','tb3','tb4','tb5');
cnt NUMBER;
BEGIN
FOR i in 1 .. tables.COUNT
LOOP
select Count(*) INTO cnt from tables(i);
insert into tb6 VALUES(tables(i),cnt);
END LOOP
END;
为此你需要 动态 SQL。
方法如下:一些示例 table(基于 Scott 的 emp
table),以及包含结果的 tb6
:
SQL> create table tb6 (val varchar2(10), cnt number);
Table created.
SQL> create table tb1 as select * from emp where deptno = 10;
Table created.
SQL> create table tb2 as select * from emp where deptno = 20;
Table created.
SQL> create table tb3 as select * from emp where deptno = 30;
Table created.
我期望哪个结果?
SQL> select deptno, count(*) from emp group by deptno order by deptno;
DEPTNO COUNT(*)
---------- ----------
10 3
20 5
30 6
程序:
SQL> create or replace procedure p_count as
2 type arr is varray(5) of varchar2(30);
3 tables arr := arr('tb1', 'tb2', 'tb3');
4 cnt number;
5 begin
6 for i in 1 .. tables.count loop
7 execute immediate 'select count(*) from ' || tables(i) into cnt;
8 insert into tb6 values(tables(i), cnt);
9 end loop;
10 end;
11 /
Procedure created.
测试:
SQL> set serveroutput on
SQL> exec p_count;
PL/SQL procedure successfully completed.
SQL> select * from tb6;
VAL CNT
---------- ----------
tb1 3
tb2 5
tb3 6
SQL>
如您所见,tb6
内容符合预期值。