PL/SQL ORACLE 中的递归函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29128342/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-19 02:46:44  来源:igfitidea点击:

Recursive function in PL/SQL ORACLE

oraclerecursionplsql

提问by Brijan Elwadhi

In which scenario recursion can be used in PL/SQL

PL/SQL可以在哪些场景下使用递归

CREATE OR REPLACE FUNCTION factorial (
  n POSITIVE
) RETURN POSITIVE
IS
BEGIN
  IF n = 1 THEN
    RETURN n;
  ELSE
  RETURN n * factorial(n-1);
  END IF;
END;
BEGIN
  FOR i IN 1..5 LOOP
    DBMS_OUTPUT.PUT_LINE(i || '! = ' || factorial(i));
  END LOOP;
END;

This will work but I want to know in real world when recursion is required in data base queries

这会起作用,但我想知道在现实世界中何时需要在数据库查询中使用递归

回答by Justin Cave

Depends what you mean by "required". A recursive algorithm can always be rewritten as a loop and a loop can always be rewritten as a recursive algorithm (assuming that the language you're working with supports both loops and function calls). Some algorithms tend to be easier to implement via recursion others tend to be easier to implement via loops.

取决于您所说的“必需”是什么意思。递归算法总是可以重写为循环,而循环总是可以重写为递归算法(假设您使用的语言支持循环和函数调用)。一些算法往往更容易通过递归实现,而另一些算法则更容易通过循环实现。

Using recursion to compute factorials in PL/SQL is a reasonable implementation choice. Using a loop would also be reasonable. If you want to do it in pure SQL rather than resorting to PL/SQL, you could also

在 PL/SQL 中使用递归计算阶乘是一个合理的实现选择。使用循环也是合理的。如果你想用纯 SQL 来做而不是诉诸 PL/SQL,你也可以

 select round( exp( sum( ln( level ) ) ) )
   from dual
connect by level <= <<some number>>

Which of various reasonable implementations you use depends on a variety of factors-- what approach you're most comfortable with, the speed of the various implementations, etc.

您使用的各种合理实现中的哪一种取决于多种因素——您最熟悉哪种方法、各种实现的速度等。