问题
I couldn't think of a practical situation to use explicit cursors in PL/SQL code. Can anybody please share some scenarios? Thanks!
回答1:
If a cursor is used more than once in a program unit, an explicit cursor allows you to code the SQL once, which is good for maintenance.
回答2:
There are two clear use cases for explicit cursors.
The first is when we want to probe for the existence of a record and handle the outcome in the main flow of our code:
open emp_cur (p_empno);
fetch emp_cur into l_emp_rec;
if emp_cur%notfound then
...
This might be neater then
begin
select e.* into l_emp_rec
from emp e
where e.empno = p_empno;
....
exception
when no_data_found then
...
Apart from anything else, what other parts of our program might hurl no_data_found
?
The other case is when we want to use bulk collection with the LIMIT clause (and almost certainly we want to use the LIMIT clause when we do bulk collection). So
open big_cursor;
loop
fetch big_cursor bulk collect into l_array limit 1000;
exit when l_array.count() = 0;
for idx in 1..l_array.count() loop
...
Explicit cursors introduce overhead into our code, so they are perceived as clunky and inefficient. But that's not always the case. In fact, if we code a bulk collect statement with an implicit cursor, Oracle will optimize that to use a LIMIT clause with a value of 100. That's not a bad default but probably we can get better performance with a higher value, 1000, 5000, even 10000. So the control we get over the LIMIT value makes it worth using the explicit cursor.
In short, we should use implicit cursors when we're happy to let Oracle make control decisions (which is a lot of the time, Oracle's pretty smart). But we should use explicit cursors when we need to exercise control over our program's behaviour.
来源:https://stackoverflow.com/questions/38494244/practical-life-examples-of-oracle-explicit-cursor-use