游标select语句中的变量

时间:2016-02-16 07:29:13

标签: oracle plsql

我试图使用PLSQL获取多个表的计数,有4个表 - testing,test1,test2,test3。

表测试具有我需要的所有表的详细信息,并使用以下程序使用游标来实现相同的目标。

declare
var varchar2(20);
var2 varchar2(20);
cursor C1 is select tab_name from testing;
begin
open C1;
loop
fetch C1 into var;
exit when C1%notfound;
select count(*) into var2 from var;
dbms_output.put_line(var2);
end loop;
end;
/

但执行时低于错误:

select count(*) into var2 from var;
                               *
ERROR at line 10:
ORA-06550: line 10, column 32:
PL/SQL: ORA-00942: table or view does not exist
ORA-06550: line 10, column 1:
PL/SQL: SQL Statement ignored

2 个答案:

答案 0 :(得分:0)

您必须将execute immediatedynamic sql一起使用。

declare
    var varchar2(50);
    var2 number;
    cursor C1 is select tab_name from testing;
begin
    open C1;
    loop
        fetch C1 into var;
        exit when C1%notfound;
        execute immediate 'select count(*) from ' || var into var2;
        dbms_output.put_line(var2);
    end loop;
end;
/

您可以使用Implicit Cursors之类的;

declare
    var number;
begin
    for i in (select tab_name from testing) loop
        execute immediate 'select count(*) from ' || i.tab_name into var;
        dbms_output.put_line(var);
    end loop;
end;
/

答案 1 :(得分:0)

set serveroutput on;
declare
var varchar2(20);
var2 varchar2(20);
cursor c is select field1 from testing;
begin
for c1 in c
loop
var2:=c1.field1;
execute immediate 'select count(*) from ' || var2 into var;
-- below query won't work as we are creating a dynamic SQL statement
 --select count(*) into var from var2;
dbms_output.put_line(var);
end loop;
end;