如何动态地将表名传递给PL SQL游标?

时间:2015-07-20 13:21:18

标签: plsql cursor oracle-sqldeveloper plsqldeveloper

我编写了一个SQL过程,我写了一个游标,每次都要动态地将表名传递给游标查询。

create or replace
PROCEDURE Add_DEN as 


v_TableName VARCHAR2(4000) := 'BO_USER_DATA';

cursor c_DEN is select * from BO_USER_DATA; // Want to pass dynamically ,now hardcoded
r_DEN c_DEN%ROWTYPE;

fetch c_DEN into r_DEN; 
v_Name := r_DEN."Name";

我可以写这样的东西

cursor c_DEN is "select * from " || v_TableName; 

任何帮助?

2 个答案:

答案 0 :(得分:2)

这里有一个例子:

declare
  TYPE curtype IS REF CURSOR;
  l_cursor curtype;
  l_param  number;
  l_key number;
  l_value number;
  l_sql varchar2(200);
begin
  /* build your sql... */
  l_sql   := 'with data as (select 1 key, 100 value from dual union select 2, 200 from dual union select 3, 300 from dual union select 3, 301 from dual)' ||
         ' select key, value from data where key = :1';
  l_param := 3;

  open l_cursor for l_sql
    using l_param;

  loop
    fetch l_cursor
      into l_key, l_value;
    exit when l_cursor%notfound;

    dbms_output.put_line(l_key||' = '||l_value);
  end loop;
  close l_cursor;
end;

结果:

3 = 300

3 = 301

答案 1 :(得分:0)

基本答案是肯定的,您可以并且根据您的示例,我建议您使用execute immediate来执行任意SQL字符串并绑定变量。 不过,我会重新考虑你是否真的需要动态设置表格,因为这通常不是真正需要的。

示例:

DECLARE
   sql_stmt    VARCHAR2(200);
   emp_id      NUMBER(4) := 7566;
   emp_rec     emp%ROWTYPE;
BEGIN
   sql_stmt := 'SELECT * FROM emp WHERE empno = :id';
   EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;
END;