[英]PL/SQL loop through cursor
My problem isn't overly complicated, but I am a newbie to PL/SQL. 我的问题不是太复杂,但我是PL / SQL的新手。
I need to make a selection from a COMPANIES table based on certain conditions. 我需要根据某些条件从COMPANIES表中进行选择。 I then need to loop through these and convert some of the fields into a different format (I have created functions for this), and finally use this converted version to join to a reference table to get the score variable I need.
然后我需要遍历这些并将一些字段转换为不同的格式(我为此创建了函数),最后使用此转换后的版本连接到引用表以获取我需要的分数变量。 So basically:
所以基本上:
select id, total_empts, bank from COMPANIES where turnover > 100000
loop through this selection 循环选择此选项
insert into MY_TABLE (select score from REF where conversion_func(MY_CURSOR.total_emps) = REF.total_emps)
This is basically what I am looking to do. 这基本上就是我要做的。 It's slightly more complicated but I'm just looking for the basics and how to approach it to get me started!
它稍微复杂一点,但我只是在寻找基础知识,以及如何处理它让我入门!
Here's the basic syntax for cursor loops in PL/SQL: 这是PL / SQL中游标循环的基本语法:
BEGIN
FOR r_company IN (
SELECT
ID,
total_emps,
bank
FROM
companies
WHERE
turnover > 100000
) LOOP
INSERT INTO
my_table
SELECT
score
FROM
ref_table
WHERE
ref.total_emps = conversion_func( r_company.total_emps )
;
END LOOP;
END;
/
You don't need to use PL/SQL to do this: 您不需要使用PL / SQL来执行此操作:
insert into my_table
select score
from ref r
join companies c
on r.total_emps on conversion_func(c.total_emps)
where c.turnover > 100000
If you have to do this in a PL/SQL loop as asked, then I'd ensure that you do as little work as possible. 如果您必须按照要求在PL / SQL循环中执行此操作,那么我将确保您尽可能少地完成工作。 I would, however, recommend bulk collect instead of the loop.
但是,我建议使用批量收集而不是循环。
begin
for xx in ( select conversion_func(total_emps) as tot_emp
from companies
where turnover > 100000 ) loop
insert into my_table
select score
from ref
where total_emps = xx.tot_emp
;
end loop;
end;
/
For either method you need one index on ref.total_emps
and preferably one on companies.turnover
对于任何一种方法,您需要在
ref.total_emps
上ref.total_emps
一个索引,最好在companies.turnover
上ref.total_emps
一个索引
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.