mysql stored procedure that calls itself recursively(递归调用自身的mysql存储过程)
问题描述
我有下表:
id | parent_id | quantity
-------------------------
1 | null | 5
2 | null | 3
3 | 2 | 10
4 | 2 | 15
5 | 3 | 2
6 | 5 | 4
7 | 1 | 9
现在我需要 mysql 中的一个存储过程,它递归地调用自己并返回计算出的数量.例如,id 6 的父值为 5,父值为 3,父值为 2.所以我需要计算 4 * 2 * 10 * 3
( = 240) 结果.
Now I need a stored procedure in mysql that calls itself recursively and returns the computed quantity.
For example the id 6 has 5 as a parent which as 3 as a parent which has 2 as a parent.
So I need to compute 4 * 2 * 10 * 3
( = 240) as a result.
我对存储过程还很陌生,以后不会经常使用它们,因为我更喜欢将业务逻辑放在程序代码中而不是数据库中.但在这种情况下,我无法避免.
I am fairly new to stored procedures and I won't use them very often in the future because I prefer having my business logic in my program code rather then in the database. But in this case I can't avoid it.
也许一个 mysql 大师(就是你)可以在几秒钟内编写一个工作语句.
Maybe a mysql guru (that's you) can hack together a working statement in a couple of seconds.
推荐答案
仅在mysql版本>=5
its work only in mysql version >= 5
存储过程声明是这样的,
the stored procedure declaration is this,
你可以给它一点改进,但这个工作:
you can give it little improve , but this working :
DELIMITER $$
CREATE PROCEDURE calctotal(
IN number INT,
OUT total INT
)
BEGIN
DECLARE parent_ID INT DEFAULT NULL ;
DECLARE tmptotal INT DEFAULT 0;
DECLARE tmptotal2 INT DEFAULT 0;
SELECT parentid FROM test WHERE id = number INTO parent_ID;
SELECT quantity FROM test WHERE id = number INTO tmptotal;
IF parent_ID IS NULL
THEN
SET total = tmptotal;
ELSE
CALL calctotal(parent_ID, tmptotal2);
SET total = tmptotal2 * tmptotal;
END IF;
END$$
DELIMITER ;
呼叫就像(设置这个变量很重要):
the calling is like (its important to set this variable) :
SET @@GLOBAL.max_sp_recursion_depth = 255;
SET @@session.max_sp_recursion_depth = 255;
CALL calctotal(6, @total);
SELECT @total;
这篇关于递归调用自身的mysql存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:递归调用自身的mysql存储过程
基础教程推荐
- SQL Server 2016更改对象所有者 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01