【问题标题】:Is there an alternative approach for cursor in my PL/SQL code?在我的 PL/SQL 代码中是否有用于光标的替代方法?
【发布时间】:2022-01-18 14:02:45
【问题描述】:
create or replace package body as p_company as

function f_insert(p_emp_no in emps.bs_emp%type, p_res out number) return number as

begin

delete from com
where com_empno = p_emp_no;

insert into com 
(...) select ... from v_com where no = p_emp_no;

end f_insert;

/* function f_update()
funtion f_validate()*/

function f_exe(p_type in varchar2, p_res out number) return number as

cursor crs_no is
select bs_emp
from emps
where bs_emp in (select s.emp_id from v_emp_det s where s.emp_type=p_type);

alt_crs crs_no%rowtype;

begin
p_res = 0;
open crs_no

loop

fetch crs_no into alt_crs
exit when crs_no%notfound;

f_insert(alt_crs.bs_emp, p_res);

/*f_update
f_validate*/

end loop;
close crs_no;

end f_exe;
end p_company;

/* 同样,我有 f_update 和 f_validate 的函数(在代码中注释)。它们在函数 f_exe 中调用。提取每个 bs_emp 并在每个函数中调用它们需要很长时间,是否有任何替代方法? */

【问题讨论】:

  • 我删除了plsqldeveloper 标签,因为您似乎不需要专门针对PL/SQL Developer 的解决方案。请在使用前检查每个标签的信息。

标签: sql oracle plsql


【解决方案1】:

逐行处理通常是缓慢的。

怎么办?不要使用循环。将光标的查询直接应用到INSERT

insert into com (...) 
select ... 
from v_com v join emps e on e.bs_emp = v.no
             join v_emp_det s on s.emp_type = p_type;

如果您同时更新和插入(似乎是这样,因为您从f_exe 调用这两个过程),您宁愿使用merge(而不是单独的update 和@987654326 @ 过程(或语句):

merge into com c
  using (select ...
         from v_com v join emps e on e.bs_emp = v.no
                      join v_emp_det s on s.emp_type = p_type
        ) x
  on (x.id = c.id)
when matched then update set
  c.name = x.name,
  c.address = x.address
when not matched then insert (id, name, address)
  values (x.id, x.name, x.address;

(我编造列名,因为您使用 (...) 而不是它们,所以我无法猜对)。


最后:为什么要使用函数?你真的向调用者返回了一些价值吗? 程序不是更合适的选择吗?

【讨论】:

  • 是的,我正在返回一些价值。在插入和更新之前,我必须删除匹配的记录。如何将其添加到代码中?
  • 在 INSERT 或 UPDATE 或 MERGE 之前运行 DELETE。
  • 我必须在日志中使用 p_emp_no,如何提取每个 p_emp_no 并显示结果?
猜你喜欢
  • 1970-01-01
  • 2010-09-30
  • 2020-04-17
  • 2017-07-07
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多