我有一个递归 mysql存储过程,我为此设置了 max_sp_recursion_depth=10.
现在,没有设置局部变量,我想知道在单次执行期间递归的级别是什么。
我认为肯定会有一个存储深度的会话变量(当你达到最高级别时你会怎么知道)但我找不到它。我会避免使用变量来逐步执行此操作。我怎么知道这个(如果有的话)系统变量?
答案 0 :(得分:2)
我知道你特意询问如何在没有用户创建的变量的情况下执行此操作但对于遇到这种想法的其他人来说,值得发布如何使用进行一个,因为它很简单:
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, 0);
-- ... 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
会话范围变量都会被上面的SET
语句递增。第一次输入时,变量未初始化,因此值为NULL
- 由IFNULL()
检查,在这种情况下将其重新分配为零。在退出之前的存储过程结束时,深度需要递减。
进一步说明
值得注意的是,SQL Server 提供了一个内置的@@NESTLEVEL
变量来执行上述操作 - 但遗憾的是MySQL似乎没有等效的。