简体   繁体   English

嵌套内部游标PL / SQL

[英]Nested Inner Cursors PL/SQL

I was just wondering when it is practical to use a nested or inner explicit cursor in PL/SQL. 我只是想知道在PL / SQL中使用嵌套或内部显式游标何时可行。 Can the situation always be avoided using JOINS? 可以始终使用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. SQL引擎具有更大的灵活性来确定如何联接两个表(或两个查询),并且比您在PL / SQL引擎中编写的代码要好得多。

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. 就个人而言,我会尽量避免这种构造,但是我倾向于与正在处理大量数据的系统一起工作,并且倾向于与那些愿意编写适当的PL / SQL和适当的SQL的人一起工作,因此可以使用联接进行查询更具可读性。 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. 另一方面,如果您要对一张小桌子进行一次性更新,编写一个执行这种循环的快速块可能会更快更容易,然后将其交给其他人进行检查,而不必验证加入两个大查询不会做任何意外的事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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