Search code examples
mysqlstored-proceduresexecutestored-functions

How to excute something what is inside a variable in MySQL?


I have a problem what I can solve in PHP but I want to solve in MySQL. Basicley I have a stored function, TASK_ASSIGN(id_task, operator).

I have an other function what SELECT exec FROM tasks. The tasks has a column exec, inside there I save TASK_ASSIGN(id_task, operator) format to execute.

I want to execute in a stored function or procedure if it is possible. Somebody can help me?


Solution

  • The solution was a stored procedure with this source:

    BEGIN
        DECLARE $execute_function VARCHAR(100);
    
        -- Get the waiting function for execution
        SELECT `exec` INTO $execute_function FROM `tasks` WHERE `id_task` = '1';
    
        -- Create a session variable with the complete select
        SET @query = CONCAT("SELECT ",$execute_function," AS result");
    
        -- Execute the custom query
        PREPARE execute_query FROM @query; 
        EXECUTE execute_query;
        DEALLOCATE PREPARE execute_query; 
    END;
    

    Thanks for wchiquito for suggesting the Prepared Statements.