【问题标题】:create a procedure with cursor as parameter创建一个以游标为参数的过程
【发布时间】:2016-01-29 12:33:25
【问题描述】:

我写了这段代码,它工作正常:

declare 
  cursor c_emp is 
  select last_name, first_name from employees;
  type c_list is table of employees.last_name%type index by binary_integer;
  type c_list2 is table of employees.first_name%type index by binary_integer;
  last_list c_list;
  first_list c_list2;
  counter integer := 0;
begin
  for i in c_emp loop
    counter := counter + 1;
    last_list(counter) := i.last_name;
    first_list(counter) := i.first_name;
    dbms_output.put_line('Employee(' || counter || '): ' || last_list(counter) || ' ' || first_list(counter));
  end loop;
end;
/

这次我尝试使用可以将表名和列插入游标的参数来创建过程。我已经尝试过了:

create or replace procedure show_data(tab_name in varchar2, data_list in varchar2)
is 
  str varchar2(100);
  str2 varchar2(100);
  column_name varchar2(100);
begin
  str := 'select ' || data_list || ' from ' || tab_name;
  for vRec in str loop
    dbms_output.put_line(str);
  end loop;
end;
/

它给出了 str 不是游标的错误。我不确定光标是否可以以这种方式完成,但从错误看来它不能。

我的代码的哪一部分是错误的,或者是因为我没有声明我的光标?但是如果我声明我的游标,我无法通过使用动态 sql 方式获取参数。

【问题讨论】:

    标签: plsql oracle11g


    【解决方案1】:

    下面的结果应该和你原来的 PL/SQL 块一样。请注意,table_name 可以是动态的,data_list 也可以是动态的,但是您需要知道data_list 中的列名才能从光标fetch 然后打印它们。

    create or replace procedure show_data(tab_name in varchar2
                                    , data_list in varchar2)
    is 
      str varchar2(100);
      str2 varchar2(100);
      column_name varchar2(100);
      TYPE cursor_ref IS REF CURSOR;
      vRec_cursor cursor_ref;
      counter integer = 0;
      last_name employee.last_name%TYPE;
      first_name employee.first_name%TYPE;
    begin
      str := 'select ' || data_list || ' from ' || tab_name;
      open vRec_cursor for str;
      loop
        FETCH vRec_cursor INTO last_name, first_name;
        EXIT WHEN vRec_cursor%NOTFOUND;
        dbms_output.put_line('Employee(' || counter || '): ' || last_name || ' ' || first_name;
        counter = counter + 1;
      end loop;
    end;
    /
    

    注意:尚未运行上述代码

    【讨论】:

    • 您好 vmachan,非常感谢您的回复。我更改了一些代码,因为缺少分号。终于可以成功编译了!!谢谢你。现在我将尝试将数组类型放入参数中,以便我可以选择可选列。再次感谢您!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-06-29
    • 2020-02-22
    • 2020-10-03
    • 1970-01-01
    相关资源
    最近更新 更多