使用 select 的游标 plsql
cursor plsql using select
我想从 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;
/
看起来你把它复杂化了。为什么不直接加入 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 中 - 你必须 select 结果 INTO
一些东西。如果您期望不止一行,请考虑使用带有 bulk collect
的集合
我想从 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;
/
看起来你把它复杂化了。为什么不直接加入 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 中 - 你必须 select 结果INTO
一些东西。如果您期望不止一行,请考虑使用带有bulk collect
的集合