温馨提示:本文翻译自stackoverflow.com,查看原文请点击:oracle - cursor plsql using select
cursor oracle plsql select

oracle - 游标plsql使用select

发布于 2020-04-10 11:24:09

我想从table1(etudiant)中获得一个值,以便使用slect在table2(employee)中使用该值,我使用cursor,但是我没有得到结果;你能帮我谢谢吗

    declare
           cle employee.id%type;
           cursor cur_test is select id from etudiant where name ='Hichem';
           no_data_found exception;
    begin

      open cur_test;

      loop
           fetch cur_test into cle;
           exit when cur_test%notfound;
      end loop;

      --dbms_output.put_line('ID IS ' ||cle);
      select * from employee where id=cle;

      if cur_test%rowcount=0 then
        close cur_test;
        raise no_data_found;      
      end if;
      close cur_test;

exception 
      when no_data_found then
        dbms_output.put_line('no data found');

end;
/

查看更多

提问者
HICHEM
被浏览
67
Littlefoot 2020-02-02 00:05

看起来您过于复杂了。您为什么不直接加入etudiant参加会议employee像这样:

begin
  for cur_r in (select e.name
                from employee e join etudiant t on t.id = e.id
                where t.name = 'Hichem'
               )
  loop
    dbms_output.put_line(cur_r.name);
  end loop;
end;
/

也许您甚至不需要循环。或者,如果您要查找的姓​​名不止一个人(Hichem在这种情况下),则可以这样做


从您的代码:

  • 一般而言,使用游标FOR循环比手动完成所有操作(声明游标变量,打开游标,获取,退出循环,关闭游标)要简单得多-如果使用游标FOR循环,则Oracle会为您完成所有操作
  • 无需明确声明no_data_found; 这是预定义的异常
  • select * from employees错误的-在PL / SQL中-您必须选择结果INTO如果您希望一行以上,请考虑将集合与bulk collect