oracle Pl/SQL 循环遍历游标的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15547342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pl/SQL Looping through the values of a cursor
提问by Cemre
CREATE OR REPLACE Function TotalIncome
( name_in IN varchar2 )
RETURN varchar2
IS
total_val number(6);
cursor c1 is
select monthly_income
from employees
where name = name_in;
BEGIN
total_val := 0;
FOR employee_rec in c1
LOOP
total_val := total_val + employee_rec.monthly_income;
END LOOP;
RETURN total_val;
END;
In this example, I am being told that that we are looping through the values of but what I dont understand is if we are looping through the values why is employee_rec.monthly_income
necessary ? Also, when I do a FETCH
on employee_rec
I seem to be getting an error so I guess they are different from each other.
在这个例子中,我被告知我们正在遍历 的值,但我不明白的是,如果我们正在遍历值,为什么有employee_rec.monthly_income
必要?另外,当我执行FETCH
on 时,employee_rec
我似乎遇到了错误,所以我猜它们彼此不同。
回答by DazzaL
you are looping through recordsin the result set.
您正在遍历结果集中的记录。
in other words:
换句话说:
FOR employee_rec in c1
means open the cursor c1
and perform a fetch on it. For each row found, assign the row record to a record variable called employee_rec
.
意味着打开游标c1
并对其执行提取。对于找到的每一行,将行记录分配给名为 的记录变量employee_rec
。
so to reference monthly_income
in that, you have to say employee_rec.monthly_income
and not just monthly_income
on its own.
所以要参考monthly_income
,你必须说employee_rec.monthly_income
,而不仅仅是monthly_income
它自己。
when I do a FETCH on employee_rec
当我对employee_rec 进行FETCH 操作时
employee_rec is not a cursor (its a variable) so you don't fetch from it. In this case the fetch from C1
is handled implicitly by the for loop, so no explicit fetch on your part is required.
employee_rec 不是游标(它是一个变量),所以你不能从中获取。在这种情况下,C1
for 循环隐式地处理了 fetch from ,因此您不需要显式 fetch。
回答by Xophmeister
You are not "looping through the values", you are looping through the records returned by your cursor. In your case, your records only contain one field -- monthly_income
-- but in general, a record can contain many fields, which you can use as you see fit in each loop iteration.
您不是“遍历值”,而是遍历游标返回的记录。在您的情况下,您的记录仅包含一个字段 -- monthly_income
-- 但通常,一条记录可以包含多个字段,您可以在每次循环迭代中根据需要使用这些字段。