我在SQL开发人员中尝试了以下程序并面临一些问题:
declare
cursor emp_complex_cur is
select e.fname,d.dlocation
from employee e, dept_location d
where e.dno=d.dnumber;
emp_max_id integer;
type emp_complex_rec is record(rname employee.fname%type,rlocation dept_location.dlocation%type);
begin
open emp_complex_cur;
for emp_complex_rec in emp_complex_cur loop
fetch emp_complex_cur into emp_complex_rec;
dbms_output.put_line('The employee id is: '||emp_complex_rec.rname||' and the employee''s location is '||emp_complex_rec.rlocation);
close emp_complex_cur;
end;
我收到错误以声明变量rname
,尽管它已在记录中正确声明。
答案 0 :(得分:1)
尝试:
begin
for emp_complex_rec in (select e.fname,
d.dlocation
from employee e
INNER JOIN dept_location d
ON (e.dno = d.dnumber))
loop
dbms_output.put_line('The employee id is: ' ||
emp_complex_rec.rname ||
' and the employee''s location is ' ||
emp_complex_rec.rlocation);
end loop;
end;
原始代码的问题在于emp_complex_rec
作为一种类型的定义与emp_complex_rec
的定义作为游标循环变量发生冲突。也不需要显式游标定义 - IMO将SELECT
置于FOR
循环中更容易,更清晰。
分享并享受。
答案 1 :(得分:0)
光标中列的名称与您在输出行中调用的名称不同,我猜你正在使用的循环是弄乱你的代码。实际上,它可能更简单:
declare
cursor emp_complex_cur is
select e.fname,d.dlocation
from employee e, dept_location d
where e.dno=d.dnumber;
emp_max_id integer;
begin
for emp_complex_rec in emp_complex_cur loop
dbms_output.put_line('The employee id is: '||emp_complex_rec.fname||' and the employee''s location is '||emp_complex_rec.dlocation);
end loop;
end;
答案 2 :(得分:0)
你似乎对一些不同的技术感到困惑。
declare
cursor emp_complex_cur is
select e.fname,d.dlocation
from employee e, dept_location d
where e.dno=d.dnumber;
emp_max_id integer;
type emp_complex_typ is record(rname employee.fname%type,rlocation dept_location.dlocation%type);
--A variable must be declared of the type you've created
emp_complex_rec emp_complex_typ;
begin
open emp_complex_cur;
--Initial fetch is needed
fetch emp_complex_cur into r_complex_rec;
while emp_complex_cur%found loop
fetch emp_complex_cur into r_complex_rec;
end loop;
close emp_complex_cur;
dbms_output.put_line('The employee id is: '||emp_complex_rec.rname||' and the employee''s location is '||emp_complex_rec.rlocation);
end;
for
循环declare
cursor emp_complex_cur is
select e.fname,d.dlocation
from employee e, dept_location d
where e.dno=d.dnumber;
begin
--no "open" required
for emp_complex_rec in emp_complex_cur loop
--no "fetch" required
null;
end loop;
--no "close" required
dbms_output.put_line('The employee id is: '||emp_complex_rec.rname||' and the employee''s location is '||emp_complex_rec.rlocation);
end;
for
循环请参阅@BobJarvis提供的答案
对于这种仅检索单个记录的情况,我更喜欢使用显式游标和单个提取。如果您的查询返回1行或100,则无关紧要,因为您只执行一行。为什么要遍历你要忽略的所有行?
declare
cursor emp_complex_cur is
select e.fname,d.dlocation
from employee e, dept_location d
where e.dno=d.dnumber;
emp_complex_rec emp_complex_cur%rowtype;
begin
open emp_complex_cur;
fetch emp_complex_cur into r_complex_rec;
close emp_complex_cur;
dbms_output.put_line('The employee id is: '||emp_complex_rec.fname||' and the employee''s location is '||emp_complex_rec.dlocation);
end;