简体   繁体   中英

Nested Inner Cursors PL/SQL

I was just wondering when it is practical to use a nested or inner explicit cursor in PL/SQL. Can the situation always be avoided using JOINS?
Any examples of Inner Cursors being used in a practical way would be great! Thank you in advance.

If you are talking about constructs like

FOR outer IN (<<query A>>)
LOOP
  FOR inner IN (<<query B that depends on data from the outer query>>)
  LOOP
    <<do something>>
  END LOOP;
END LOOP;

It will essentially (ie barring some corner case where the optimizer picks a bad plan and it's not practical to fix that any other way) always be more efficient to combine the two queries and do a join. The SQL engine has far more flexibility to figure out how to join two tables (or two queries) and is much better at it than code you write in the PL/SQL engine.

That said, if you're dealing with small volumes of data and you (or the other developers that are maintaining the system) would have trouble following a combined query, there may be valid reasons from a maintainability perspective to code loops like this. It's likely to be an approach that developers coming from other languages are going to be more comfortable with reading, for example. If the data volumes are small, the additional overhead of manually coding a nested loop join is generally going to be relatively small and can still yield code that performs acceptably.

Personally, I'd try to avoid this sort of construct if at all possible, but I tend to work with systems that are processing large amounts of data and with people that are comfortable writing proper PL/SQL and proper SQL so queries with joins are going to be more readable. On the other hand, if you're doing a one-off update of a small table, it may be quicker and easier to write a quick block that does this sort of loop and hand that off to someone else to review rather than having to verify that joining two large queries doesn't do anything unexpected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM