How To have Dynamic SQL in MySQL Stored Procedure

前端 未结 3 1799
无人共我
无人共我 2020-11-21 22:10

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

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 22:45

    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.

提交回复
热议问题