将 PL/SQL 参数作为 SCHEMA NAME 传递

Pass PL/SQL parameter as SCHEMA NAME

我正在尝试通过过程输入将变量模式名称发送到光标 这是我蹩脚的尝试,但你可以看到我想做什么:

CREATE OR REPLACE PROCEDURE HOUSEKEEPING 
(SCHEMANAME in varchar2)

IS

CURSOR data_instances  IS  select table_name 
from SCHEMANAME.table_name where TYPE='PERMANENT' and rownum<200 ;

BEGIN
    DBMS_OUTPUT.PUT_LINE(SCHEMANAME);
END;
/

它抛出预期

PL/SQL: ORA-00942: table or view does not exist

是否有合法的方法使模式名称作为变量使用?谢谢

有办法;您将需要某种 dynamic SQL 因为您不能那样使用模式(或对象)名称。例如,您可以改用 refcursor。

样本table:

SQL> create table table_name as
  2  select 'EMP' table_name, 'PERMANENT' type from dual union all
  3  select 'DEPT'          , 'TEMPORARY'      from dual union all
  4  select 'BONUS'         , 'PERMANENT'      from dual;

Table created.

程序;请注意我首先编写 SELECT 语句的方式(以便我可以显示它并检查它是否正确),然后在 OPEN 中使用它。循环是为了……好吧,循环遍历光标。我只是显示 table 个我找到的名字 - 你可能会做一些 更聪明.

SQL> create or replace procedure housekeeping (par_schemaname in varchar2)
  2  is
  3    l_str        varchar2(500);
  4    l_rc         sys_refcursor;
  5    l_table_name varchar2(30);
  6  begin
  7    l_str := 'select table_name from ' ||
  8              dbms_assert.schema_name(upper(par_schemaname)) ||
  9             '.table_name where type = ''PERMANENT'' and rownum < 200';
 10    open l_rc for l_str;
 11
 12    loop
 13      fetch l_rc into l_table_name;
 14      exit when l_rc%notfound;
 15
 16      dbms_output.put_line(l_table_name);
 17    end loop;
 18    close l_rc;
 19  end;
 20  /

Procedure created.

测试:

SQL> set serveroutput on
SQL> exec housekeeping('SCOTT');
EMP
BONUS

PL/SQL procedure successfully completed.

SQL>