我有一个递归 mysql 存储过程,我已为其设置了 max_sp_recursion_depth=10。
现在,不设置局部变量,我想知道在单次执行期间递归的级别是多少。
我认为肯定有一个存储深度的 session 变量(当你达到最大水平时你怎么知道)但我找不到它。我会避免使用变量来逐步执行此操作。我怎么知道这个(如果有的话)系统变量?
最佳答案
我知道您特别询问了如何在没有用户创建的变量的情况下执行此操作 - 但对于遇到此问题的其他人来说,值得发布如何使用来执行此操作一个,因为它相当简单:
CREATE PROCEDURE sp_recursive
BEGIN
// ... DECLAREs here
-- Set maximum recursion depth (max is 255)
SET @@SESSION.max_sp_recursion_depth = 10;
-- Increment current recursion depth
SET @recursion_depth = IFNULL(@recursion_depth + 1, 1);
-- ... More stored procedure code
-- Decrement current recursion depth. Note: Care must be taken to ensure this line
-- is *always* executed at the end of the stored procedure.
SET @recursion_depth = @recursion_depth - 1;
END
解释
每次进入存储过程时,@recursion_depth
session 范围的变量都会通过上面的 SET
语句递增。第一次输入时,变量未初始化,因此值为 NULL
- 这是由 IFNULL()
检查的,它将它重新分配给一个案件。在存储过程结束前退出时,深度需要递减。
进一步说明
值得注意的是,SQL Server 确实提供了一个内置的 @@NESTLEVEL
变量来执行上述操作 - 但不幸的是,MySQL 似乎没有等效项。
关于mysql - 如何深入mysql存储过程递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10351065/