Home > Database > Mysql Tutorial > body text

How to Implement a Recursive Stored Procedure in MySQL for Calculating Quantity Hierarchy?

Barbara Streisand
Release: 2024-10-31 19:23:02
Original
469 people have browsed it

How to Implement a Recursive Stored Procedure in MySQL for Calculating Quantity Hierarchy?

Recursive Stored Procedure for Calculating Quantity Hierarchy

In MySQL, creating a recursive stored procedure to compute quantities for nested hierarchical structures is a challenge that can be overcome using a carefully crafted procedure. Consider the given table, where each row represents an item with an associated quantity and potential parent.

Recursive Stored Procedure

To recursively traverse this tree-like structure and calculate the total quantity, the following stored procedure can be implemented:

<code class="mysql">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 ;</code>
Copy after login

Procedure Execution

To enable recursion, it's crucial to adjust MySQL settings:

<code class="mysql">SET @@GLOBAL.max_sp_recursion_depth = 255;
SET @@session.max_sp_recursion_depth = 255;</code>
Copy after login

Once these settings are configured, the stored procedure can be invoked like this:

<code class="mysql">CALL calctotal(6, @total);
SELECT @total;</code>
Copy after login

Recursive Calculation Example

For the given sample data, where item 6 is a child of item 5, which is a child of item 3, and so on, the stored procedure will recursively calculate the total quantity as follows:

4 * 2 * 10 * 3 = 240
Copy after login

Therefore, the result of calling the procedure with number = 6 will be 240.

The above is the detailed content of How to Implement a Recursive Stored Procedure in MySQL for Calculating Quantity Hierarchy?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template