3

I have several MySQL tables that maintains a tree structure of records. Each record have an ID and a Parent field. I want to write a stored function to get the parent ID, given a record ID.

The following is my first attempt, and it's incorrect. My problem is I do not know how to use variable table name.

delimiter $$

create function parent(
    tableName varchar(15),
    nodeId    int
) returns int
begin
    declare p int;
    select parent into p from tableName where id=nodeId;
    return p;
end$$

Please help. Thanks!

6
  • Possibly related: stackoverflow.com/questions/6593078/… Commented Feb 25, 2014 at 2:20
  • 1
    Multiple tables with the same structure are a bad idea. You should be storing them in one table with an additional column specifying the "tablename". Commented Feb 25, 2014 at 2:22
  • That's true, but this is for research performance evaluation. Basically, there are several tables with the same structure but different parameters. I use these tables to measure the performance of my algorithm. Commented Feb 25, 2014 at 2:25
  • @Jeff But once you have dynamic SQL in the mix all your measurements will be off anyway Commented Feb 25, 2014 at 2:26
  • How so? It's just a variable for table name. Commented Feb 25, 2014 at 2:27

1 Answer 1

2

After some research, apparently a stored function will not work in this case due to the fact stored functions cannot execute dynamic SQL. I change my implementation to a stored procedure.

delimiter $$

create procedure parent(tableName varchar(15), nodeId int)
begin
    set @s := concat('select parent from ', tableName, ' where id =', nodeId);
    prepare query from @s;
    execute query;
    deallocate prepare query;
end$$

delimiter ;
Sign up to request clarification or add additional context in comments.

2 Comments

So how do you get the value now?
@AntonioCS That's a procedure, it will output the sql result. If you want only the value to use it in another SQL (and you're sure your procedure extracts one value) I've added an output parameter to the procedure, and then created a function which actually calls the procedure and returns the output, I had to use this trick in order to build a recursive function, and it works ;)

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.