Home > Software engineering >  Well, I have a problem about recursion in MySql, about creating a recursive factorial function. it g
Well, I have a problem about recursion in MySql, about creating a recursive factorial function. it g

Time:11-27

DELIMITER //
create function FactorialR (n int) returns int
begin
    declare resultado int default 1;
    set resultado=FactorialR(n-1)*n;

 return resultado;
 end//
 DELIMITER ;

CodePudding user response:

MySQL functions are not allowed to be recursive. Recursive stored functions in MySQL

CodePudding user response:

You are not to use recursion, but you can always use simple loops

Of course you can use Pocedures which allow recursive calls

create function FactorialR (n int) returns int
begin
    declare resultado BIGint default 1;
    DECLARE m int DEFAuLT  1;
    
loop_label:  LOOP
      IF  m = n THEN 
          LEAVE  loop_label;
      END  IF;
            
      SET  m = m   1;
      set resultado=resultado*m;
  END LOOP;
 return resultado;
 end
SELECT FactorialR(4)
| FactorialR(4) |
| ------------: |
|            24 |

db<>fiddle here

  • Related