Home > Database > Mysql Tutorial > How can we create a MySQL stored procedure to calculate factorial?

How can we create a MySQL stored procedure to calculate factorial?

WBOY
Release: 2023-08-23 08:13:02
forward
1602 people have browsed it

How can we create a MySQL stored procedure to calculate factorial?

mysql> DELIMITER //
mysql> CREATE PROCEDURE get_factorial(IN N INT)
    -> BEGIN
    ->    SET @@GLOBAL.max_sp_recursion_depth = 255;
    ->    SET @@session.max_sp_recursion_depth = 255;
    ->
    ->    CALL factorial_recursive (N, @factorial);
    ->
    ->    SELECT @factorial;
    -> END //
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER //
mysql> CREATE PROCEDURE factorial_recursive(IN N INT,OUT factorial INT)
    -> BEGIN
    ->    IF N = 1 THEN
    ->       SET factorial := 1;
    ->    ELSE
    ->       CALL factorial_recursive (N-1, factorial);
    ->       SET factorial := N * factorial;
    ->    END IF;
    -> END //
Query OK, 0 rows affected (0.00 sec)

mysql> DELIMITER ;
mysql> Call get_factorial(10);
+--------------+
| @factorial   |
+--------------+
|      3628800 |
+--------------+
1 row in set (0.11 sec)
Query OK, 0 rows affected (0.12 sec)

mysql> Call get_factorial(5);
+-------------+
| @factorial  |
+-------------+
|         120 |
+-------------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
Copy after login

The above is the detailed content of How can we create a MySQL stored procedure to calculate factorial?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template