MySQL giới hạn đệ quy mặc định = 0. Cần tăng max_sp_recursion_depth (tối đa 255).
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 //
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)
Gọi thủ tục:
mysql> CALL get_factorial(10); +--------------+ | @factorial | +--------------+ | 3628800 | +--------------+ mysql> CALL get_factorial(5); +-------------+ | @factorial | +-------------+ | 120 | +-------------+
Dùng 2 thủ tục: wrapper set recursion depth, thủ tục đệ quy tính toán thực tế.