1

I have a database with a table which looks somewhat like this :

Root   |   Connector
  A    |      B
  B    |      C
  C    |      D
  D    |      E
  E    |      -

So i want to retrieve the chain for any given root till the connector is blank

For example : Chain of A means a->B->C->D->E whereas Chain of C means C->D->E

I am using mysql database.

Thanks in advance

1
  • 1
    What programming language are you using? Commented Dec 17, 2012 at 11:50

2 Answers 2

3

I just try with loop structure in Mysql and got success. Posting to share only--

CREATE PROCEDURE `root_connect`(IN init char(1),OUT str char(15))
BEGIN
    set @startChar:=(select connector from tableName where root = init);
    set @endloop := "no";
    set @fullchar:= @startChar;
    set @newchar:= "";  
    if (@startChar !="-" OR @startChar =null) then 
        WHILE (@endloop = "no") DO                  
            set @newchar :=(select connector from tableName where root = @startChar);       
            if(@newchar = '-') THEN
                set @endloop := "yes";
            else
                set @fullchar:= concat(@fullchar,"-",@newchar);
            end if;         
            set @startChar := @newchar;     
        END WHILE;
    end if;
        select @fullchar;
END
Sign up to request clarification or add additional context in comments.

Comments

1

Since MySQL does not allow the users to create a recursive function, let me show you using stored procedure:

Assuming the table you are working on is named "test".

DELIMITER $$

DROP PROCEDURE IF EXISTS build_chain$$
CREATE PROCEDURE build_chain(init CHAR(1))
BEGIN
    IF init != '-' THEN
        SET @r := (SELECT DISTINCT(root) FROM test WHERE root = init);
        SET @search_type := TRUE;
        SET @result := @r;
    END IF;

    SET @r := (SELECT DISTINCT(connector) FROM test WHERE root = @r AND connector != '-');
    SET @result = CONCAT_WS('->', @result, @r);
    SET @search_type = IF(@search_type, FALSE, TRUE);
    IF @r IS NOT NULL THEN CALL build_chain('-'); ELSE SELECT @result AS result_chain; END IF;

END$$

DELIMITER ;

Usage:

SET max_sp_recursion_depth = 255;
CALL build_chain('a');

Result (the chain) is stored in @result variable.

Note: you can also build the chain using programming language other than MySQL.

1 Comment

Hi Husni... i did create this store procedure, but i am unable to execute these commands : SET max_sp_recursion_depth = 255; CALL build_chain('a');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.