You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向cursor传递参数并从Department、Employee两张表提取对应记录

带参数游标实现部门关联员工信息查询方法

实现逻辑

你要实现的需求核心是显式游标传参+嵌套循环遍历,具体操作规则如下:

  • 定义游标时在游标名称后用括号声明入参,推荐用%type绑定表字段类型,避免后续表结构变更导致类型不兼容
  • 打开游标时在括号内传入实际参数值,即可实现按传入条件查询对应记录
  • 外层循环遍历所有部门拿到部门编号,内层循环把当前部门编号作为参数传入员工游标,即可查询该部门下所有员工

优化后实现代码(支持遍历所有部门的对应员工)

set serveroutput on;
declare
-- 部门游标:无参数,查询所有部门
cursor dept_cursor is 
select department_id, department_name from hr.departments;
deptno hr.departments.department_id%type;
deptname hr.departments.department_name%type;

-- 员工游标:带部门ID入参,查询指定部门下的员工
cursor emp_cursor(deptid hr.departments.department_id%type) is
select employee_id, first_name, salary, job_id from hr.employees where department_id = deptid;
empno hr.employees.employee_id%type;
empname hr.employees.first_name%type;
sal hr.employees.salary%type;
jobid hr.employees.job_id%type;

begin
-- 外层循环遍历所有部门
open dept_cursor;
loop
fetch dept_cursor into deptno, deptname;
exit when dept_cursor%notfound;
dbms_output.put_line('=== 部门编号:'|| deptno||' 部门名称:'||deptname || ' ===');

-- 内层循环:传入当前部门ID,查询该部门员工
open emp_cursor(deptno);
loop
fetch emp_cursor into empno, empname, sal, jobid;
exit when emp_cursor%notfound;
dbms_output.put_line('员工编号:'|| empno||' 员工姓名:'||empname ||' 员工薪资:' ||sal||' 岗位:'||jobid);
end loop;
close emp_cursor;

end loop;
close dept_cursor;

end;
/

原参考代码说明

你提供的参考代码是固定查询10号部门的信息和对应员工,已经正确实现了游标传参的核心逻辑:

  1. 定义dept_cursor和emp_cursor时都声明了deptid入参
  2. 打开游标时传入固定值10作为查询条件
    如果只需要查询单个指定部门的信息,直接使用该参考代码即可正常运行。

内容的提问来源于stack exchange,提问作者AlbertAlex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 03:18:01