我在pl / sql bloc中使用游标时遇到问题。我有一张名为Angajati(employees)
的桌子,我需要显示每个部门的所有员工,例如:
Dep 10:
John Smith
King Steven
Dep 20:
Henry King
William
...
当我尝试这样做时,我收到了ORA-06502: PL/SQL: numeric or value error: number precision too large
之类的错误,或者我的脚本没有显示任何内容。这是我的代码:
declare
dep_min angajati.id_departament %type;
dep_max angajati.id_departament %type;
id_min angajati.id_angajat %type;
id_max angajati.id_angajat %type;
i angajati.id_angajat %type;
cursor c is select nume, prenume, id_departament, id_angajat from angajati where id_angajat=i;
r c%rowtype;
begin
select min(id_departament), max(id_departament) into dep_min, dep_max from angajati;
select min(id_angajat), max(id_angajat) into id_min, id_max from angajati;
open c;
loop
dbms_output.put_line('...');
dbms_output.put_line('Departamentul ' || dep_min);
for i in id_min..id_max
loop
fetch c into r;
if(r.id_departament=dep_min) then
dbms_output.put_line(r.nume || ' ' || r.prenume );
else null;
end if;
exit when id_min>id_max;
end loop;
dep_min:=dep_min+10;
end loop;
close c;
end;
/
答案 0 :(得分:0)
要获得这样的结果,最好使用以下内容:
Dep 10:
John Smith
King Steven
Dep 20:
Henry King
William
PL / SQL代码:
BEGIN
FOR dep IN (SELECT id_departament,
COUNT(*) cnt
FROM angajati
GROUP BY id_departament
ORDER BY id_departament) LOOP
dbms_output.put_line('Dep ' || dep.id_departament || '. Count employee ' || dep.cnt);
FOR empl IN (SELECT * FROM angajati WHERE id_departament = dep.id_departament) LOOP
dbms_output.put_line(empl.nume || ' ' || empl.prenume);
END LOOP;
END LOOP;
END;
答案 1 :(得分:0)
正如Stepan在上面的回答中所提到的,这可以通过更简单的方式来完成,但如果你坚持要通过你的方法。可能这有帮助。但这也可以通过SQL来完成。尽可能总是喜欢SQL而不是PLSQL。我现在没有工作空间,所以请原谅任何语法错误。
DECLARE
dep_min angajati.id_departament%type;
dep_max angajati.id_departament%type;
id_min angajati.id_angajat%type;
id_max angajati.id_angajat%type;
i angajati.id_angajat%type;
BEGIN
SELECT MIN(id_departament),
MAX(id_departament)
INTO dep_min,
dep_max
FROM angajati;
SELECT MIN(id_angajat),
MAX(id_angajat)
INTO id_min,
id_max
FROM angajati;
dbms_output.put_line('...');
dbms_output.put_line('Departamentul ' || dep_min);
FOR k IN id_min..id_max
LOOP
FOR J IN
(SELECT nume,
prenume,
id_departament,
id_angajat
FROM angajati
WHERE id_angajat=i
)
LOOP
IF(j.id_departament=dep_min) THEN
dbms_output.put_line(j.nume || ' ' || j.prenume );
ELSE
NULL;
END IF;
END LOOP;
dep_min:=dep_min+10;
END LOOP;
END;
/