问题
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!
回答1:
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 ;
来源:https://stackoverflow.com/questions/22003322/variable-table-name-mysql-stored-function