【问题标题】:Oracle - Get function parameter value in cursorOracle - 获取游标中的函数参数值
【发布时间】:2026-02-14 17:00:01
【问题描述】:

我有一个包,我在其中创建了一个这样的函数

create or replace package pk_server_control
is
function fn_get_employees_by_consultant(consultant_id number) return number;
end;
-----------------------------------------------------------------
create or replace package body pk_server_control
is

 **function fn_get_employees_by_consultant(consultant_id number)
 return number
 is
  cursor employees is select c.CST_NAME, a.NO_OF_EMPLOYEES from NISHAN_LDS_ACCOUNT a join NISHAN_LDS_CONSULTANT c
                      on c.CONSULTANT_ID = a.FK1_CONSULTANT_ID where c.CONSULTANT_ID =consultant_id ;
 total number := 0; **

 begin
   for data in employees
   loop
    total := total + data.NO_OF_EMPLOYEES;
   end loop;

   return total;
 end;
end;


begin
dbms_output.put_line(pk_server_control.fn_get_employees_by_consultant(1));
end;

我需要从函数“fn_get_employees_by_consultant”的参数“consultant_id number”中获取值到光标“”的“consultant_id”中。运行时,它不会给出错误,也不会传递值。请帮我解决这个问题:)

【问题讨论】:

  • 您是否将consultant_id 添加到光标的select 列表中?
  • “没有通过值”是指没有结果,还是太多,或者其他什么?它看起来像一个简单的名称冲突,它将返回表中的所有行......例如see this。 (可能是重复的?)
  • 不相关,我可以指出您可以使用 SUM 直接在 SQL 中执行此操作,而不是循环。逐行是缓慢的。
  • 它没有通过任何结果。
  • 所以你的块打印为零 - 或什么都没有?如果您手动运行游标查询,您会看到什么,既与您拥有的完全一样,又将最后一个变量更改为文字 1?

标签: oracle function plsql parameters cursor


【解决方案1】:

试试这个

create or replace package pk_server_control
is
 function fn_get_employees_by_consultant(consultant_id number) return number;
end;
-----------------------------------------------------------------
create or replace package body pk_server_control
is
  function fn_get_employees_by_consultant(consultant_id number)
  return number
  is
   val number := consultant_id;
   cursor employees is select c.CST_NAME, a.NO_OF_EMPLOYEES from NISHAN_LDS_ACCOUNT a join NISHAN_LDS_CONSULTANT c
                       on c.CONSULTANT_ID = a.FK1_CONSULTANT_ID where c.CONSULTANT_ID =val;
  total number := 0;

  begin
    for data in employees 
    loop
     total := total + data.NO_OF_EMPLOYEES;
    end loop;

    return total;
  end;
end;


begin
 dbms_output.put_line(pk_server_control.fn_get_employees_by_consultant(3));
end;

【讨论】: