Variable Table Name MySQL Stored Function

你说的曾经没有我的故事 提交于 2019-12-12 05:28:50

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!