MySQL uses stored procedures for Recursive queries (2)

Source: Internet
Author: User

I have only recently started working heavily
With stored procedures and functions in MySQL. After years in
Oracle world with advanced stored procedures, functions and packages,
I 've had to come to grips with the same comings of MySQL. One of those
Is recursive functions. MySQL allows recursive stored procedures,
Not recursive stored functions. Here is my workaround...

First create your main logic as a stored procedure with an out variable:

DELIMITER |
CREATE PROCEDURE my_recursive_proc(a_some_parameter INTEGER, OUT a_result INTEGER)
BEGIN
DECLARE v_my_number INTEGER DEFAULT 0;
-- Have to set max_sp_recursion_depth inside the stored procedure
SET max_sp_recursion_depth := 20;
SET v_my_number := v_my_number + a_some_parameter;
IF v_my_number < 100 THEN
CALL my_recursive_proc(10, v_my_number);
END IF;
SET a_result := v_my_number;
END |
DELIMITER ;

So now I have a recursive procedure that callitself adding 10
The initial number until we get to 100. In the real world we 'd be doing
Something serious like descending through related child records until we
Find some search result. What I really want now is a function I can
Call in a where clause somewhere.

Here's all we have to do:

CREATE FUNCTION my_recursive_func(a_some_parameter INTEGER)
RETURNS INTEGER
BEGIN
DECLARE v_result INTEGER DEFAULT 0;
CALL my_recursive_proc(a_some_parameter, v_result);
RETURN v_result;
END |
DELIMITER ;

Now in my select statements I can do:
SELECT * FROM my_table WHERE my_recursive_func(some_column) = 100;

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.