How To have Dynamic SQL in MySQL Stored Procedure

Brian Boatright picture Brian Boatright · Oct 10, 2008 · Viewed 126.9k times · Source

How do you build and use dynamic sql in a MySQL stored procedure?

Answer

TimoSolo picture TimoSolo · Apr 20, 2011

After 5.0.13, in stored procedures, you can use dynamic SQL:

delimiter // 
CREATE PROCEDURE dynamic(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
    SET @s = CONCAT('SELECT ',col,' FROM ',tbl );
    PREPARE stmt FROM @s;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END
//
delimiter ;

Dynamic SQL does not work in functions or triggers. See the MySQL documentation for more uses.