在循环输出 Oracle PLSQL 函数时需要帮助
Posted
技术标签:
【中文标题】在循环输出 Oracle PLSQL 函数时需要帮助【英文标题】:Need help in looping output for Oracle PLSQL Function 【发布时间】:2020-11-09 04:04:43 【问题描述】:我目前正在研究 oracle PLSQL 功能,以列出项目编号、职位和参与每个项目的员工姓名。到目前为止,我能够获得所需的输出,但只能在一个一个调用之后才能做到。如何在我的代码中实现一个循环以允许它一次调用它。
[当前代码]
create or replace procedure PROJECTGROUPS(projectid IN WorksOn.P#%TYPE)
IS
PID Project.P#%TYPE;
PNAME Project.PTitle%TYPE;
ENAME Employee.Name%TYPE;
finalRow VARCHAR(2000);
CURSOR query is
select Employee.Name from Employee
left outer join WorksOn On Employee.E# = WorksOn.E#
where WorksOn.P# = projectid
order by Employee.Name ASC
fetch first 20 rows only;
--
--
--
--
--
begin
select P#, PTitle into PID, PNAME from project where project.p# = projectid;
finalRow:= PID || ' ' || PNAME || ': ';
--
open query;
loop
fetch query into ENAME;
if query%NOTFOUND then exit;
end if;
finalRow:= finalRow || CASE WHEN SUBSTR(finalRow ,-2) <> ': ' THEN ', ' END || ENAME;
end loop;
close query;
dbms_output.put_line(finalRow);
return;
end PROJECTGROUPS;
/
execute PROJECTGROUPS(1001)
execute PROJECTGROUPS(1002)
execute PROJECTGROUPS(1003)
execute PROJECTGROUPS(1004)
execute PROJECTGROUPS(1005)
execute PROJECTGROUPS(1006)
show error
[电流输出]
SQL> execute PROJECTGROUPS(1001)
1001 Computation: Alvin, Peter
PL/SQL procedure successfully completed.
SQL> execute PROJECTGROUPS(1002)
1002 Study methods: Bob, Robert
PL/SQL procedure successfully completed.
SQL> execute PROJECTGROUPS(1003)
1003 Racing car: Robert
PL/SQL procedure successfully completed.
SQL> execute PROJECTGROUPS(1004)
1004 Football: Douglass, Eadger, Robert
PL/SQL procedure successfully completed.
SQL> execute PROJECTGROUPS(1005)
1005 Swimming: Robert
PL/SQL procedure successfully completed.
SQL> execute PROJECTGROUPS(1006)
1006 Training: Aban
如何循环我的代码,以便我可以使用执行 PROJECTGROUPS 调用它们。
【问题讨论】:
【参考方案1】:您可以使用单个查询从每个项目中获取 20 名员工,如下所示,并在循环中使用它们来打印如下:
create or replace procedure PROJECTGROUPS(projectid IN WorksOn.P#%TYPE) -- you can remove input parameter as it is not used anywhere now
IS
BEGIN
FOR q in
(Select proj_detail, LISTAGG(name, ', ') WITHIN GROUP (ORDER BY NAME) AS NAMES from
(select project.p# || ' ' || project.ptitle as proj_detail,
Employee.Name,
Row_number() over (partition by project.p# order by employee.name) as rn
from project
Join WorksOn on project.p# = WorksOn.P#
join employee On Employee.E# = WorksOn.E#)
Where rn <= 20
GROUP BY PROJ_DETAIL)
LOOP
DBMS_OUTPUT.PUT_LINE(Q.PROJ_DETAIL || ': ' || Q.NAMES);
END LOOP;
END;
/
【讨论】:
有什么我需要在这个声明中声明的吗? 已经尝试过您的代码,得到了当前问题:27 月 1 日 PL/SQL:SQL 语句被忽略 27 月 1 日 PLS-00394:FETCH 语句的 INTO 列表中的值数量错误跨度> 谢谢你的代码似乎产生了预期的结果。如果可能,是否可以出于学习目的解释您的代码。 我创建了查询,它提供了输出所需的两个组件并在循环中使用它。使用 FOR 循环非常简单。如果它解决了您的问题,请接受答案。以上是关于在循环输出 Oracle PLSQL 函数时需要帮助的主要内容,如果未能解决你的问题,请参考以下文章
Oracle-4 - :超级适合初学者的入门级笔记:plsql,基本语法,记录类型,循环,游标,异常处理,存储过程,存储函数,触发器